mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds music play history persistence and reporting endpoints
This commit is contained in:
1 parent
9919965a73
commit
009a0c8156
55 files changed
+6426
-3
No files matched your search
@@ -0,0 +1,181 @@
|
||||
# Lumina API
|
||||
|
||||
- [Lumina API](#lumina-api)
|
||||
- [Play History](#play-history)
|
||||
- [Start Play](#start-play)
|
||||
- [Start Play Request](#start-play-request)
|
||||
- [Start Play Response](#start-play-response)
|
||||
- [Get Play Record](#get-play-record)
|
||||
- [Get Play Record Request](#get-play-record-request)
|
||||
- [Get Play Record Response](#get-play-record-response)
|
||||
- [Report Play Progress](#report-play-progress)
|
||||
- [Report Play Progress Request](#report-play-progress-request)
|
||||
- [Report Play Progress Response](#report-play-progress-response)
|
||||
- [Complete Play](#complete-play)
|
||||
- [Complete Play Request](#complete-play-request)
|
||||
- [Complete Play Response](#complete-play-response)
|
||||
- [Stop Play](#stop-play)
|
||||
- [Stop Play Request](#stop-play-request)
|
||||
- [Stop Play Response](#stop-play-response)
|
||||
- [Concurrent Reports](#concurrent-reports)
|
||||
|
||||
## Play History
|
||||
|
||||
The play history records what the player played, how far it reached, how long the user listened, and whether the play completed or stopped. It is not a playback session: it stores no queue, current index, repeat or shuffle state, and it never restores playback. A play record belongs to the user that started it, and only that user can read it or report its progress, completion or stop.
|
||||
|
||||
### Start Play
|
||||
|
||||
#### Start Play Request
|
||||
|
||||
```js
|
||||
POST api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
Records the start of a play of the track identified by the route. The library, artist, album and track Ids are taken from the route, so a request cannot substitute them with values from a body. The album and track are checked against the route scope, and the library ownership policy is evaluated, so a play is only recorded for a track of a library the current user can access. The request has no body.
|
||||
|
||||
#### Start Play Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
|
||||
"trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
|
||||
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
|
||||
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
|
||||
"artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
|
||||
"status": "InProgress",
|
||||
"lastPositionInSeconds": 0,
|
||||
"listenedDurationInSeconds": 0,
|
||||
"startedOnUtc": "2026-10-19T12:00:00.0000000Z",
|
||||
"endedOnUtc": null,
|
||||
"updatedOnUtc": null
|
||||
}
|
||||
```
|
||||
|
||||
The returned `id` identifies the play record in the progress, complete, stop and read routes. A track that does not exist, or that does not belong to the route's library, artist and album, is reported as not found with `AlbumNotFound` or `TrackNotFound`.
|
||||
|
||||
### Get Play Record
|
||||
|
||||
#### Get Play Record Request
|
||||
|
||||
```js
|
||||
GET api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
Returns the play record identified by the route, when it belongs to the current user. A record of another user is reported as not found, exactly like a record that does not exist, so a guessed identifier never reveals the existence of another user's play.
|
||||
|
||||
#### Get Play Record Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f",
|
||||
"trackId": "9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f",
|
||||
"libraryId": "3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
|
||||
"albumId": "e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f",
|
||||
"artistId": "d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a",
|
||||
"status": "Stopped",
|
||||
"lastPositionInSeconds": 92.5,
|
||||
"listenedDurationInSeconds": 92.5,
|
||||
"startedOnUtc": "2026-10-19T12:00:00.0000000Z",
|
||||
"endedOnUtc": "2026-10-19T12:01:32.5000000Z",
|
||||
"updatedOnUtc": "2026-10-19T12:01:32.5000000Z"
|
||||
}
|
||||
```
|
||||
|
||||
The response is private to the authenticated user: it carries `Cache-Control: private, no-store` and `Vary: Authorization`.
|
||||
|
||||
### Report Play Progress
|
||||
|
||||
#### Report Play Progress Request
|
||||
|
||||
```js
|
||||
PUT api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"positionInSeconds": 92.5,
|
||||
"listenedDurationInSeconds": 92.5
|
||||
}
|
||||
```
|
||||
|
||||
Reports the last position and the listened duration of an in-progress play of the current user. The listened duration can never decrease. A record of another user, or a record that does not exist, is reported as not found.
|
||||
|
||||
#### Report Play Progress Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
The response body is an empty JSON object.
|
||||
|
||||
A play that is no longer in progress is reported as a conflict (`409`) with `PlayIsNotInProgress`. A report that read the play before another report completed or stopped it is also reported as a conflict (`409`), with `ConcurrencyConflict`, instead of reverting the stored state.
|
||||
|
||||
### Complete Play
|
||||
|
||||
#### Complete Play Request
|
||||
|
||||
```js
|
||||
PUT api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"positionInSeconds": 354,
|
||||
"listenedDurationInSeconds": 354
|
||||
}
|
||||
```
|
||||
|
||||
Marks an in-progress play of the current user as completed, with the last position and the listened duration of the track.
|
||||
|
||||
#### Complete Play Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
The response body is an empty JSON object. A play that is no longer in progress, or that another report changed after this one read it, is reported as a conflict (`409`) with `PlayIsNotInProgress` or `ConcurrencyConflict`.
|
||||
|
||||
### Stop Play
|
||||
|
||||
#### Stop Play Request
|
||||
|
||||
```js
|
||||
PUT api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"positionInSeconds": 92.5,
|
||||
"listenedDurationInSeconds": 92.5
|
||||
}
|
||||
```
|
||||
|
||||
Marks an in-progress play of the current user as stopped before the track completed, with the last position and the listened duration the user reached.
|
||||
|
||||
#### Stop Play Response
|
||||
|
||||
```js
|
||||
200 Ok
|
||||
```
|
||||
|
||||
The response body is an empty JSON object. A play that is no longer in progress, or that another report changed after this one read it, is reported as a conflict (`409`) with `PlayIsNotInProgress` or `ConcurrencyConflict`.
|
||||
|
||||
### Concurrent Reports
|
||||
|
||||
Every play record carries an optimistic concurrency version. A progress, complete or stop report reads the stored version, and the update is applied only when the stored version still matches. If another report ended or changed the play between the read and the write, the update affects no row and the request is reported as `409 ConcurrencyConflict`. A late progress report therefore never reverts a completed or stopped play, never clears its end time, and never lowers its listened duration. A busy or locked SQLite write is reported the same way.
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
PUT {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/complete
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"positionInSeconds": 354,
|
||||
"listenedDurationInSeconds": 354
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
GET {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
PUT {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/progress
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"positionInSeconds": 92.5,
|
||||
"listenedDurationInSeconds": 92.5
|
||||
}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
POST {{host}}/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
@@ -0,0 +1,8 @@
|
||||
PUT {{host}}/api/v1/users/me/music-play-history/plays/2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f/stop
|
||||
Authorization: Bearer {{ACCESS_TOKEN}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"positionInSeconds": 92.5,
|
||||
"listenedDurationInSeconds": 92.5
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.Common;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Repository entity for a recorded play of a track.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("Id: {Id}; TrackId: {TrackId}; Status: {Status}")]
|
||||
public class MusicPlayRecordEntity : IStorageEntity, IAuditableEntity
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the Id of the play record.
|
||||
/// </summary>
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the user that started the play.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the track that was played.
|
||||
/// </summary>
|
||||
public required Guid TrackId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the media library that contains the track.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the album that contains the track.
|
||||
/// </summary>
|
||||
public required Guid AlbumId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the Id of the artist that produced the track.
|
||||
/// </summary>
|
||||
public required Guid ArtistId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the state of the recorded play.
|
||||
/// </summary>
|
||||
public PlaybackRecordStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the last position reported by the player, in milliseconds. It is stored as a whole number of milliseconds so that the
|
||||
/// stored value is independent of the persistence medium's support for time values.
|
||||
/// </summary>
|
||||
public long LastPositionMilliseconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the duration the user has listened to, in milliseconds. It is stored as a whole number of milliseconds so that the
|
||||
/// stored value is independent of the persistence medium's support for time values.
|
||||
/// </summary>
|
||||
public long ListenedDurationMilliseconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time when the play completed or stopped, if it has ended.
|
||||
/// </summary>
|
||||
public DateTime? EndedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the version of the stored row. It is used as an optimistic concurrency token, so that a report that read the play
|
||||
/// before another report ended it can never overwrite the newer state.
|
||||
/// </summary>
|
||||
public long Version { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the time and date when the entity was added. It is also the date and time when the play started.
|
||||
/// </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; }
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Interface for the repository for recorded music plays.
|
||||
/// </summary>
|
||||
public interface IMusicPlayRecordRepository : IRepository<MusicPlayRecordEntity>,
|
||||
IInsertRepositoryAction<MusicPlayRecordEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the play record 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 play record to get.</param>
|
||||
/// <param name="userId">The Id of the user the play record must belong to.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved record should be tracked by the persistence medium, so that changes to it 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 play record identified by <paramref name="id"/> and owned by <paramref name="userId"/>,
|
||||
/// <see langword="null"/> when no such record exists, or an error.
|
||||
/// </returns>
|
||||
Task<Result<MusicPlayRecordEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the play record of the user identified by <paramref name="userId"/>, when the record belongs to that user and still holds the
|
||||
/// version it was read with.
|
||||
/// </summary>
|
||||
/// <param name="data">The play record whose editable values are applied to the stored record.</param>
|
||||
/// <param name="userId">The Id of the user the play record must belong to.</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 update, or an error.</returns>
|
||||
Task<Result<Updated>> UpdateForUserAsync(MusicPlayRecordEntity data, Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -150,6 +150,11 @@ public interface IUnitOfWork
|
||||
/// </summary>
|
||||
IUserSettingsRepository UserSettingsRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the music play record repository.
|
||||
/// </summary>
|
||||
IMusicPlayRecordRepository MusicPlayRecordRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
@@ -14,5 +14,6 @@ public static partial class Errors
|
||||
public static Error ErrorPersistingMediaLibrary => Error.Failure(description: nameof(ErrorPersistingMediaLibrary));
|
||||
public static Error ErrorPersistingAuthorizationRole => Error.Failure(description: nameof(ErrorPersistingAuthorizationRole));
|
||||
public static Error UniqueConstraintViolation => Error.Conflict(description: nameof(UniqueConstraintViolation));
|
||||
public static Error ConcurrencyConflict => Error.Conflict(description: nameof(ConcurrencyConflict));
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="CompletePlayRequest"/>.
|
||||
/// </summary>
|
||||
public static class CompletePlayRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="CompletePlayCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playRecordId">The Id of the play record, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static CompletePlayCommand ToCommand(this CompletePlayRequest request, string? playRecordId)
|
||||
{
|
||||
return new CompletePlayCommand(
|
||||
playRecordId,
|
||||
request.PositionInSeconds,
|
||||
request.ListenedDurationInSeconds
|
||||
);
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="MusicPlayRecordEntity"/>.
|
||||
/// </summary>
|
||||
public static class MusicPlayRecordEntityMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="MusicPlayRecord"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either a successfully converted <see cref="MusicPlayRecord"/>, or an error message.
|
||||
/// </returns>
|
||||
public static Result<MusicPlayRecord> ToDomainEntity(this MusicPlayRecordEntity repositoryEntity)
|
||||
{
|
||||
return MusicPlayRecord.Create(
|
||||
MusicPlayRecordId.Create(repositoryEntity.Id),
|
||||
UserId.Create(repositoryEntity.UserId),
|
||||
TrackId.Create(repositoryEntity.TrackId),
|
||||
LibraryId.Create(repositoryEntity.LibraryId),
|
||||
AlbumId.Create(repositoryEntity.AlbumId),
|
||||
ArtistId.Create(repositoryEntity.ArtistId),
|
||||
repositoryEntity.Status,
|
||||
MusicPlayPosition.Create(TimeSpan.FromMilliseconds(repositoryEntity.LastPositionMilliseconds)),
|
||||
TimeSpan.FromMilliseconds(repositoryEntity.ListenedDurationMilliseconds),
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.EndedOnUtc),
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
Optional<DateTime>.FromNullable(repositoryEntity.UpdatedOnUtc)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="repositoryEntity"/> to <see cref="PlayRecordResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static PlayRecordResponse ToResponse(this MusicPlayRecordEntity repositoryEntity)
|
||||
{
|
||||
return new PlayRecordResponse(
|
||||
repositoryEntity.Id,
|
||||
repositoryEntity.TrackId,
|
||||
repositoryEntity.LibraryId,
|
||||
repositoryEntity.AlbumId,
|
||||
repositoryEntity.ArtistId,
|
||||
repositoryEntity.Status,
|
||||
TimeSpan.FromMilliseconds(repositoryEntity.LastPositionMilliseconds).TotalSeconds,
|
||||
TimeSpan.FromMilliseconds(repositoryEntity.ListenedDurationMilliseconds).TotalSeconds,
|
||||
repositoryEntity.CreatedOnUtc,
|
||||
repositoryEntity.EndedOnUtc,
|
||||
repositoryEntity.UpdatedOnUtc
|
||||
);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="MusicPlayRecord"/>.
|
||||
/// </summary>
|
||||
public static class MusicPlayRecordMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="domainEntity"/> to <see cref="MusicPlayRecordEntity"/>.
|
||||
/// </summary>
|
||||
/// <param name="domainEntity">The domain entity to be converted.</param>
|
||||
/// <returns>The converted repository entity.</returns>
|
||||
public static MusicPlayRecordEntity ToRepositoryEntity(this MusicPlayRecord domainEntity)
|
||||
{
|
||||
return new MusicPlayRecordEntity
|
||||
{
|
||||
Id = domainEntity.Id.Value,
|
||||
UserId = domainEntity.UserId.Value,
|
||||
TrackId = domainEntity.TrackId.Value,
|
||||
LibraryId = domainEntity.LibraryId.Value,
|
||||
AlbumId = domainEntity.AlbumId.Value,
|
||||
ArtistId = domainEntity.ArtistId.Value,
|
||||
Status = domainEntity.Status,
|
||||
// Stored time is truncated to whole milliseconds instead of rounded, so a retried report of the same fractional second maps to
|
||||
// the same stored value and is not rejected as a decrease by the domain.
|
||||
LastPositionMilliseconds = (long)domainEntity.LastPosition.Offset.TotalMilliseconds,
|
||||
ListenedDurationMilliseconds = (long)domainEntity.ListenedDuration.TotalMilliseconds,
|
||||
EndedOnUtc = domainEntity.EndedOnUtc.HasValue ? domainEntity.EndedOnUtc.Value : null,
|
||||
Version = 1,
|
||||
CreatedOnUtc = domainEntity.CreatedOnUtc,
|
||||
CreatedBy = Guid.Empty,
|
||||
// The audit columns are owned by the auditing interceptor, which stamps only the rows that actually changed, so they are never mapped here.
|
||||
UpdatedOnUtc = null,
|
||||
UpdatedBy = null
|
||||
};
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ReportPlayProgressRequest"/>.
|
||||
/// </summary>
|
||||
public static class ReportPlayProgressRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="ReportPlayProgressCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playRecordId">The Id of the play record, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static ReportPlayProgressCommand ToCommand(this ReportPlayProgressRequest request, string? playRecordId)
|
||||
{
|
||||
return new ReportPlayProgressCommand(
|
||||
playRecordId,
|
||||
request.PositionInSeconds,
|
||||
request.ListenedDurationInSeconds
|
||||
);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="StopPlayRequest"/>.
|
||||
/// </summary>
|
||||
public static class StopPlayRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="StopPlayCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="playRecordId">The Id of the play record, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
public static StopPlayCommand ToCommand(this StopPlayRequest request, string? playRecordId)
|
||||
{
|
||||
return new StopPlayCommand(
|
||||
playRecordId,
|
||||
request.PositionInSeconds,
|
||||
request.ListenedDurationInSeconds
|
||||
);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
|
||||
|
||||
/// <summary>
|
||||
/// Command for reporting that a play of a track by the current user reached its end.
|
||||
/// </summary>
|
||||
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
|
||||
/// <param name="PositionInSeconds">The last position reported by the player, in seconds.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds.</param>
|
||||
[DebuggerDisplay("PlayRecordId: {PlayRecordId}; PositionInSeconds: {PositionInSeconds}")]
|
||||
public record CompletePlayCommand(
|
||||
string? PlayRecordId,
|
||||
double? PositionInSeconds,
|
||||
double? ListenedDurationInSeconds
|
||||
) : ICommand;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to report that a play of a track by the current user reached its end.
|
||||
/// </summary>
|
||||
public class CompletePlayCommandHandler : ICommandHandler<CompletePlayCommand, Result<Updated>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<CompletePlayCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompletePlayCommandHandler"/> 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 CompletePlayCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<CompletePlayCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to report that a play of a track by the current user reached its end.
|
||||
/// </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 update, or an error message.</returns>
|
||||
public async Task<Result<Updated>> HandleAsync(CompletePlayCommand 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 and the reported times are valid before this point.
|
||||
Guid playRecordId = Guid.Parse(command.PlayRecordId!);
|
||||
|
||||
// The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one.
|
||||
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.GetByIdForUserAsync(playRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlayRecordResult.IsFailure)
|
||||
return getPlayRecordResult.Errors;
|
||||
if (getPlayRecordResult.Value is null)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
|
||||
|
||||
Result<MusicPlayRecord> toDomainEntityResult = getPlayRecordResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
MusicPlayRecord playRecord = toDomainEntityResult.Value;
|
||||
|
||||
Result<Updated> completeResult = playRecord.Complete(
|
||||
MusicPlayPosition.Create(TimeSpan.FromSeconds(command.PositionInSeconds!.Value)),
|
||||
TimeSpan.FromSeconds(command.ListenedDurationInSeconds!.Value));
|
||||
if (completeResult.IsFailure)
|
||||
return completeResult.Errors;
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.UpdateForUserAsync(playRecord.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.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 playRecord.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="CompletePlayCommand"/>.
|
||||
/// </summary>
|
||||
public class CompletePlayCommandValidator : AbstractValidator<CompletePlayCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompletePlayCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public CompletePlayCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlayRecordId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlayRecordId)
|
||||
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
|
||||
.When(command => command.PlayRecordId is not null && command.PlayRecordId.Length > 0)
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.NotNull()
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionCannotBeNull);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.Must(position => position is null || (double.IsFinite(position.Value) && position.Value >= 0))
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionMustBeNonNegative);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.Must(position => position is null || position.Value <= TimeSpan.MaxValue.TotalSeconds)
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionIsOutOfRange);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.NotNull()
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationCannotBeNull);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.Must(listenedDuration => listenedDuration is null || (double.IsFinite(listenedDuration.Value) && listenedDuration.Value >= 0))
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationMustBeNonNegative);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.Must(listenedDuration => listenedDuration is null || listenedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationIsOutOfRange);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Command for reporting the progress of a play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
|
||||
/// <param name="PositionInSeconds">The last position reported by the player, in seconds.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user has listened to, in seconds.</param>
|
||||
[DebuggerDisplay("PlayRecordId: {PlayRecordId}; PositionInSeconds: {PositionInSeconds}")]
|
||||
public record ReportPlayProgressCommand(
|
||||
string? PlayRecordId,
|
||||
double? PositionInSeconds,
|
||||
double? ListenedDurationInSeconds
|
||||
) : ICommand;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to report the progress of a play of a track by the current user.
|
||||
/// </summary>
|
||||
public class ReportPlayProgressCommandHandler : ICommandHandler<ReportPlayProgressCommand, Result<Updated>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<ReportPlayProgressCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportPlayProgressCommandHandler"/> 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 ReportPlayProgressCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<ReportPlayProgressCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to report the progress of a play of a track by 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 update, or an error message.</returns>
|
||||
public async Task<Result<Updated>> HandleAsync(ReportPlayProgressCommand 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 and the reported times are valid before this point.
|
||||
Guid playRecordId = Guid.Parse(command.PlayRecordId!);
|
||||
|
||||
// The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one.
|
||||
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.GetByIdForUserAsync(playRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlayRecordResult.IsFailure)
|
||||
return getPlayRecordResult.Errors;
|
||||
if (getPlayRecordResult.Value is null)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
|
||||
|
||||
Result<MusicPlayRecord> toDomainEntityResult = getPlayRecordResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
MusicPlayRecord playRecord = toDomainEntityResult.Value;
|
||||
|
||||
Result<Updated> reportProgressResult = playRecord.ReportProgress(
|
||||
MusicPlayPosition.Create(TimeSpan.FromSeconds(command.PositionInSeconds!.Value)),
|
||||
TimeSpan.FromSeconds(command.ListenedDurationInSeconds!.Value));
|
||||
if (reportProgressResult.IsFailure)
|
||||
return reportProgressResult.Errors;
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.UpdateForUserAsync(playRecord.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.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 playRecord.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="ReportPlayProgressCommand"/>.
|
||||
/// </summary>
|
||||
public class ReportPlayProgressCommandValidator : AbstractValidator<ReportPlayProgressCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportPlayProgressCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public ReportPlayProgressCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlayRecordId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlayRecordId)
|
||||
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
|
||||
.When(command => command.PlayRecordId is not null && command.PlayRecordId.Length > 0)
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.NotNull()
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionCannotBeNull);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.Must(position => position is null || (double.IsFinite(position.Value) && position.Value >= 0))
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionMustBeNonNegative);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.Must(position => position is null || position.Value <= TimeSpan.MaxValue.TotalSeconds)
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionIsOutOfRange);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.NotNull()
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationCannotBeNull);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.Must(listenedDuration => listenedDuration is null || (double.IsFinite(listenedDuration.Value) && listenedDuration.Value >= 0))
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationMustBeNonNegative);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.Must(listenedDuration => listenedDuration is null || listenedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationIsOutOfRange);
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Command for recording the start of a play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library that contains the track, taken from the route.</param>
|
||||
/// <param name="ArtistId">The unique identifier of the artist that produced the track, taken from the route.</param>
|
||||
/// <param name="AlbumId">The unique identifier of the album that contains the track, taken from the route.</param>
|
||||
/// <param name="TrackId">The unique identifier of the track that started playing, taken from the route.</param>
|
||||
[DebuggerDisplay("TrackId: {TrackId}")]
|
||||
public record StartPlayCommand(
|
||||
string? LibraryId,
|
||||
string? ArtistId,
|
||||
string? AlbumId,
|
||||
string? TrackId
|
||||
) : ICommand;
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.DomainEvents;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to record the start of a play of a track by the current user.
|
||||
/// </summary>
|
||||
public class StartPlayCommandHandler : ICommandHandler<StartPlayCommand, Result<PlayRecordResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<StartPlayCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartPlayCommandHandler"/> 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="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public StartPlayCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<StartPlayCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to record the start of a play of a track by 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="PlayRecordResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlayRecordResponse>> HandleAsync(StartPlayCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> validationResult = _validator.Validate(command);
|
||||
if (validationResult.Count > 0)
|
||||
return validationResult;
|
||||
|
||||
// An authenticated request must always carry a user identity.
|
||||
Guid? currentUserId = _currentUserService.UserId;
|
||||
if (currentUserId is null)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
Guid userId = currentUserId.Value;
|
||||
|
||||
// The validator guarantees that the route identifiers are non-empty Guids before this point.
|
||||
Guid libraryId = Guid.Parse(command.LibraryId!);
|
||||
Guid artistId = Guid.Parse(command.ArtistId!);
|
||||
Guid albumId = Guid.Parse(command.AlbumId!);
|
||||
Guid trackId = Guid.Parse(command.TrackId!);
|
||||
|
||||
// Admins can report plays of the tracks of all libraries; for everyone else, only the tracks of the libraries they own. Authorization
|
||||
// is evaluated before any album or track is read, so an unauthorized caller cannot tell whether the route's album or track exists.
|
||||
bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
|
||||
if (!canAccessLibrary)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// The album is loaded first, so that the artist and the library named by the request are enforced before the track itself is read. This is
|
||||
// the same resource scoping the track read uses, so a play can never reference a track through another library, artist or album.
|
||||
Result<AlbumEntity?> getAlbumResult = await _unitOfWork.AlbumRepository
|
||||
.GetByIdAsync(albumId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getAlbumResult.IsFailure)
|
||||
return getAlbumResult.Errors;
|
||||
if (getAlbumResult.Value is null)
|
||||
return DomainErrors.Music.AlbumNotFound;
|
||||
AlbumEntity existingAlbum = getAlbumResult.Value;
|
||||
if (existingAlbum.LibraryId != libraryId || existingAlbum.ArtistId != artistId)
|
||||
return DomainErrors.Music.AlbumNotFound;
|
||||
|
||||
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;
|
||||
TrackEntity existingTrack = getTrackResult.Value;
|
||||
if (existingTrack.AlbumId != albumId || existingTrack.LibraryId != libraryId)
|
||||
return DomainErrors.Music.TrackNotFound;
|
||||
|
||||
// Create the play record, which also raises the domain event announcing the start of the play.
|
||||
MusicPlayRecord playRecord = MusicPlayRecord.Create(
|
||||
UserId.Create(userId),
|
||||
TrackId.Create(trackId),
|
||||
LibraryId.Create(libraryId),
|
||||
AlbumId.Create(albumId),
|
||||
ArtistId.Create(artistId));
|
||||
|
||||
Result<Created> insertResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.InsertAsync(playRecord.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 playRecord.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
// Reading does not need the aggregate: the persisted row is read directly and mapped to the response, so the response carries the
|
||||
// timestamps the auditing interceptor actually stored instead of the in-memory aggregate's values.
|
||||
Result<MusicPlayRecordEntity?> getPersistedPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.GetByIdForUserAsync(playRecord.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPersistedPlayRecordResult.IsFailure)
|
||||
return getPersistedPlayRecordResult.Errors;
|
||||
if (getPersistedPlayRecordResult.Value is null)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
|
||||
|
||||
return getPersistedPlayRecordResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="StartPlayCommand"/>.
|
||||
/// </summary>
|
||||
public class StartPlayCommandValidator : AbstractValidator<StartPlayCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartPlayCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public StartPlayCommandValidator()
|
||||
{
|
||||
// Validates the identifier of the media library that contains the track, taken from the route.
|
||||
RuleFor(command => command.LibraryId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.LibraryId)
|
||||
.Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
|
||||
.When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the artist that produced the track, taken from the route.
|
||||
RuleFor(command => command.ArtistId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.ArtistId)
|
||||
.Must(artistId => Guid.TryParse(artistId, out Guid parsedArtistId) && parsedArtistId != Guid.Empty)
|
||||
.When(command => command.ArtistId is not null && command.ArtistId.Length > 0)
|
||||
.WithError(Errors.Music.ArtistIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the album that contains the track, taken from the route.
|
||||
RuleFor(command => command.AlbumId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.AlbumId)
|
||||
.Must(albumId => Guid.TryParse(albumId, out Guid parsedAlbumId) && parsedAlbumId != Guid.Empty)
|
||||
.When(command => command.AlbumId is not null && command.AlbumId.Length > 0)
|
||||
.WithError(Errors.Music.AlbumIdCannotBeEmpty);
|
||||
|
||||
// Validates the identifier of the track that started playing, taken from the route.
|
||||
RuleFor(command => command.TrackId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.TrackId)
|
||||
.Must(trackId => Guid.TryParse(trackId, out Guid parsedTrackId) && parsedTrackId != Guid.Empty)
|
||||
.When(command => command.TrackId is not null && command.TrackId.Length > 0)
|
||||
.WithError(Errors.Music.TrackIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Command for reporting that a play of a track by the current user stopped before the track completed.
|
||||
/// </summary>
|
||||
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
|
||||
/// <param name="PositionInSeconds">The last position reported by the player, in seconds.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds.</param>
|
||||
[DebuggerDisplay("PlayRecordId: {PlayRecordId}; PositionInSeconds: {PositionInSeconds}")]
|
||||
public record StopPlayCommand(
|
||||
string? PlayRecordId,
|
||||
double? PositionInSeconds,
|
||||
double? ListenedDurationInSeconds
|
||||
) : ICommand;
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Events;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
|
||||
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate.ValueObjects;
|
||||
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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to report that a play of a track by the current user stopped before the track completed.
|
||||
/// </summary>
|
||||
public class StopPlayCommandHandler : ICommandHandler<StopPlayCommand, Result<Updated>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<StopPlayCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopPlayCommandHandler"/> 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 StopPlayCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<StopPlayCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to report that a play of a track by the current user stopped before the track completed.
|
||||
/// </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 update, or an error message.</returns>
|
||||
public async Task<Result<Updated>> HandleAsync(StopPlayCommand 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 and the reported times are valid before this point.
|
||||
Guid playRecordId = Guid.Parse(command.PlayRecordId!);
|
||||
|
||||
// The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one.
|
||||
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.GetByIdForUserAsync(playRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlayRecordResult.IsFailure)
|
||||
return getPlayRecordResult.Errors;
|
||||
if (getPlayRecordResult.Value is null)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
|
||||
|
||||
Result<MusicPlayRecord> toDomainEntityResult = getPlayRecordResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
MusicPlayRecord playRecord = toDomainEntityResult.Value;
|
||||
|
||||
Result<Updated> stopResult = playRecord.Stop(
|
||||
MusicPlayPosition.Create(TimeSpan.FromSeconds(command.PositionInSeconds!.Value)),
|
||||
TimeSpan.FromSeconds(command.ListenedDurationInSeconds!.Value));
|
||||
if (stopResult.IsFailure)
|
||||
return stopResult.Errors;
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.UpdateForUserAsync(playRecord.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.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 playRecord.GetDomainEvents())
|
||||
_domainEventsQueue.Enqueue(domainEvent);
|
||||
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="StopPlayCommand"/>.
|
||||
/// </summary>
|
||||
public class StopPlayCommandValidator : AbstractValidator<StopPlayCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopPlayCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public StopPlayCommandValidator()
|
||||
{
|
||||
RuleFor(command => command.PlayRecordId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PlayRecordId)
|
||||
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
|
||||
.When(command => command.PlayRecordId is not null && command.PlayRecordId.Length > 0)
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.NotNull()
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionCannotBeNull);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.Must(position => position is null || (double.IsFinite(position.Value) && position.Value >= 0))
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionMustBeNonNegative);
|
||||
|
||||
RuleFor(command => command.PositionInSeconds)
|
||||
.Must(position => position is null || position.Value <= TimeSpan.MaxValue.TotalSeconds)
|
||||
.WithError(Errors.MusicPlayHistory.PlaybackPositionIsOutOfRange);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.NotNull()
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationCannotBeNull);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.Must(listenedDuration => listenedDuration is null || (double.IsFinite(listenedDuration.Value) && listenedDuration.Value >= 0))
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationMustBeNonNegative);
|
||||
|
||||
RuleFor(command => command.ListenedDurationInSeconds)
|
||||
.Must(listenedDuration => listenedDuration is null || listenedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
|
||||
.WithError(Errors.MusicPlayHistory.ListenedDurationIsOutOfRange);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting a recorded play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="PlayRecordId">The Id of the play record, taken from the route.</param>
|
||||
[DebuggerDisplay("PlayRecordId: {PlayRecordId}")]
|
||||
public record GetPlayRecordQuery(
|
||||
string? PlayRecordId
|
||||
) : IQuery;
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
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;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get a recorded play of a track by the current user.
|
||||
/// </summary>
|
||||
public class GetPlayRecordQueryHandler : IQueryHandler<GetPlayRecordQuery, Result<PlayRecordResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IValidator<GetPlayRecordQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlayRecordQueryHandler"/> 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 GetPlayRecordQueryHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IValidator<GetPlayRecordQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get a recorded play of a track by 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 requested <see cref="PlayRecordResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<PlayRecordResponse>> HandleAsync(GetPlayRecordQuery 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 playRecordId = Guid.Parse(query.PlayRecordId!);
|
||||
|
||||
// The record is read without tracking and scoped to the current user, so a record of another user is indistinguishable from a missing one.
|
||||
Result<MusicPlayRecordEntity?> getPlayRecordResult = await _unitOfWork.MusicPlayRecordRepository
|
||||
.GetByIdForUserAsync(playRecordId, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
if (getPlayRecordResult.IsFailure)
|
||||
return getPlayRecordResult.Errors;
|
||||
if (getPlayRecordResult.Value is null)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
|
||||
|
||||
return getPlayRecordResult.Value.ToResponse();
|
||||
}
|
||||
}
|
||||
+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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetPlayRecordQuery"/>.
|
||||
/// </summary>
|
||||
public class GetPlayRecordQueryValidator : AbstractValidator<GetPlayRecordQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlayRecordQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetPlayRecordQueryValidator()
|
||||
{
|
||||
RuleFor(query => query.PlayRecordId)
|
||||
.NotEmpty()
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
|
||||
RuleFor(query => query.PlayRecordId)
|
||||
.Must(playRecordId => Guid.TryParse(playRecordId, out Guid parsedPlayRecordId) && parsedPlayRecordId != Guid.Empty)
|
||||
.When(query => query.PlayRecordId is not null && query.PlayRecordId.Length > 0)
|
||||
.WithError(Errors.MusicPlayHistory.PlayRecordIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to report that a play of a track by the current user reached its end.
|
||||
/// </summary>
|
||||
/// <param name="PositionInSeconds">The last position reported by the player, in seconds. Required.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds. Required.</param>
|
||||
[DebuggerDisplay("PositionInSeconds: {PositionInSeconds}; ListenedDurationInSeconds: {ListenedDurationInSeconds}")]
|
||||
public sealed record CompletePlayRequest(
|
||||
double? PositionInSeconds,
|
||||
double? ListenedDurationInSeconds
|
||||
);
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to report the progress of a play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="PositionInSeconds">The last position reported by the player, in seconds. Required.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user has listened to, in seconds. Required.</param>
|
||||
[DebuggerDisplay("PositionInSeconds: {PositionInSeconds}; ListenedDurationInSeconds: {ListenedDurationInSeconds}")]
|
||||
public sealed record ReportPlayProgressRequest(
|
||||
double? PositionInSeconds,
|
||||
double? ListenedDurationInSeconds
|
||||
);
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request to report that a play of a track by the current user stopped before the track completed.
|
||||
/// </summary>
|
||||
/// <param name="PositionInSeconds">The last position reported by the player, in seconds. Required.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user listened to, in seconds. Required.</param>
|
||||
[DebuggerDisplay("PositionInSeconds: {PositionInSeconds}; ListenedDurationInSeconds: {ListenedDurationInSeconds}")]
|
||||
public sealed record StopPlayRequest(
|
||||
double? PositionInSeconds,
|
||||
double? ListenedDurationInSeconds
|
||||
);
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a recorded play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the play record.</param>
|
||||
/// <param name="TrackId">The Id of the track that was played.</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="ArtistId">The Id of the artist that produced the track.</param>
|
||||
/// <param name="Status">The state of the recorded play.</param>
|
||||
/// <param name="LastPositionInSeconds">The last position reported by the player, in seconds.</param>
|
||||
/// <param name="ListenedDurationInSeconds">The duration the user has listened to, in seconds.</param>
|
||||
/// <param name="StartedOnUtc">The date and time when the play started.</param>
|
||||
/// <param name="EndedOnUtc">The date and time when the play completed or stopped, if it has ended.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the play record was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("Id: {Id}; TrackId: {TrackId}; Status: {Status}")]
|
||||
public sealed record PlayRecordResponse(
|
||||
Guid Id,
|
||||
Guid TrackId,
|
||||
Guid LibraryId,
|
||||
Guid AlbumId,
|
||||
Guid ArtistId,
|
||||
PlaybackRecordStatus Status,
|
||||
double LastPositionInSeconds,
|
||||
double ListenedDurationInSeconds,
|
||||
DateTime StartedOnUtc,
|
||||
DateTime? EndedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,95 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Common.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="MusicPlayRecordEntity"/> entity.
|
||||
/// </summary>
|
||||
public class MusicPlayRecordConfiguration : IEntityTypeConfiguration<MusicPlayRecordEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="MusicPlayRecordEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<MusicPlayRecordEntity> builder)
|
||||
{
|
||||
builder.ToTable("MusicPlayRecords");
|
||||
builder.HasKey(playRecord => playRecord.Id);
|
||||
builder.Property(playRecord => playRecord.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);
|
||||
|
||||
builder.Property(playRecord => playRecord.UserId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(1);
|
||||
|
||||
builder.Property(playRecord => playRecord.TrackId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(2);
|
||||
|
||||
builder.Property(playRecord => playRecord.LibraryId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(playRecord => playRecord.AlbumId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(playRecord => playRecord.ArtistId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(5);
|
||||
|
||||
builder.Property(playRecord => playRecord.Status)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnOrder(6);
|
||||
|
||||
builder.Property(playRecord => playRecord.LastPositionMilliseconds)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(7);
|
||||
|
||||
builder.Property(playRecord => playRecord.ListenedDurationMilliseconds)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(8);
|
||||
|
||||
builder.Property(playRecord => playRecord.EndedOnUtc)
|
||||
.HasColumnOrder(9);
|
||||
|
||||
// The version is the optimistic concurrency token: every update increments it, and an update whose loaded version no longer matches
|
||||
// the stored one affects no row and fails, instead of reverting a play that another report already completed or stopped.
|
||||
builder.Property(playRecord => playRecord.Version)
|
||||
.IsRequired()
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnOrder(10);
|
||||
|
||||
// Audit.
|
||||
builder.Property(playRecord => playRecord.CreatedOnUtc)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(11);
|
||||
|
||||
builder.Property(playRecord => playRecord.CreatedBy)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(12);
|
||||
|
||||
builder.Property(playRecord => playRecord.UpdatedOnUtc)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(13);
|
||||
|
||||
builder.Property(playRecord => playRecord.UpdatedBy)
|
||||
.HasDefaultValue(null)
|
||||
.HasColumnOrder(14);
|
||||
|
||||
// The referenced entities are kept by Id only, without foreign keys, so a play survives the deletion of the track it references and the
|
||||
// statistics of the listening history still count it.
|
||||
// Enables the chronological reads of the plays of a user, which the statistics are built from.
|
||||
builder.HasIndex(playRecord => new { playRecord.UserId, playRecord.CreatedOnUtc });
|
||||
|
||||
// Enables the reads of the plays of a track, which the per track statistics are built from.
|
||||
builder.HasIndex(playRecord => playRecord.TrackId);
|
||||
}
|
||||
}
|
||||
+3537
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Lumina.DataAccess.Common.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddsMusicPlayHistory : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "MusicPlayRecords",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
UserId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
TrackId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
LibraryId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
AlbumId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
ArtistId = table.Column<Guid>(type: "TEXT", nullable: false),
|
||||
Status = table.Column<string>(type: "TEXT", maxLength: 20, nullable: false),
|
||||
LastPositionMilliseconds = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
ListenedDurationMilliseconds = table.Column<long>(type: "INTEGER", nullable: false),
|
||||
EndedOnUtc = table.Column<DateTime>(type: "TEXT", nullable: true),
|
||||
Version = 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_MusicPlayRecords", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MusicPlayRecords_TrackId",
|
||||
table: "MusicPlayRecords",
|
||||
column: "TrackId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_MusicPlayRecords_UserId_CreatedOnUtc",
|
||||
table: "MusicPlayRecords",
|
||||
columns: new[] { "UserId", "CreatedOnUtc" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "MusicPlayRecords");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -960,6 +960,80 @@ namespace Lumina.DataAccess.Common.Migrations
|
||||
b.ToTable("MusicLibraryScanItemMetadata", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.MusicPlayRecordEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(0);
|
||||
|
||||
b.Property<Guid>("AlbumId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(4);
|
||||
|
||||
b.Property<Guid>("ArtistId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(5);
|
||||
|
||||
b.Property<Guid>("CreatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(12);
|
||||
|
||||
b.Property<DateTime>("CreatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(11);
|
||||
|
||||
b.Property<DateTime?>("EndedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(9);
|
||||
|
||||
b.Property<long>("LastPositionMilliseconds")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(7);
|
||||
|
||||
b.Property<Guid>("LibraryId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(3);
|
||||
|
||||
b.Property<long>("ListenedDurationMilliseconds")
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(8);
|
||||
|
||||
b.Property<string>("Status")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(6);
|
||||
|
||||
b.Property<Guid>("TrackId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(2);
|
||||
|
||||
b.Property<Guid?>("UpdatedBy")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(14);
|
||||
|
||||
b.Property<DateTime?>("UpdatedOnUtc")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(13);
|
||||
|
||||
b.Property<Guid>("UserId")
|
||||
.HasColumnType("TEXT")
|
||||
.HasColumnOrder(1);
|
||||
|
||||
b.Property<long>("Version")
|
||||
.IsConcurrencyToken()
|
||||
.HasColumnType("INTEGER")
|
||||
.HasColumnOrder(10);
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("TrackId");
|
||||
|
||||
b.HasIndex("UserId", "CreatedOnUtc");
|
||||
|
||||
b.ToTable("MusicPlayRecords", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary.TrackContributorEntity", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.DataAccess.Common.Persistence;
|
||||
using Lumina.DataAccess.Core.UoW;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.DataAccess.Core.Repositories.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for recorded music plays.
|
||||
/// </summary>
|
||||
internal sealed class MusicPlayRecordRepository : IMusicPlayRecordRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MusicPlayRecordRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public MusicPlayRecordRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the play record 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 play record to get.</param>
|
||||
/// <param name="userId">The Id of the user the play record must belong to.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved record should be tracked by the persistence medium, so that changes to it 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 play record identified by <paramref name="id"/> and owned by <paramref name="userId"/>,
|
||||
/// <see langword="null"/> when no such record exists, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<MusicPlayRecordEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
|
||||
{
|
||||
// The user is part of the filter rather than a check performed after the read, so the storage medium never returns a record that
|
||||
// belongs to another user in the first place.
|
||||
IQueryable<MusicPlayRecordEntity> query = _luminaDbContext.MusicPlayRecords
|
||||
.Where(playRecord => playRecord.Id == id && playRecord.UserId == userId);
|
||||
if (!shouldTrackEntities)
|
||||
query = query.AsNoTracking();
|
||||
return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new play record.
|
||||
/// </summary>
|
||||
/// <param name="data">The play record to add.</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<Created>> InsertAsync(MusicPlayRecordEntity data, CancellationToken cancellationToken)
|
||||
{
|
||||
bool doesPlayRecordExist = await _luminaDbContext.MusicPlayRecords
|
||||
.AnyAsync(playRecord => playRecord.Id == data.Id, cancellationToken).ConfigureAwait(false);
|
||||
if (doesPlayRecordExist)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordAlreadyExists;
|
||||
|
||||
_luminaDbContext.MusicPlayRecords.Add(data);
|
||||
return Result.Created;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the play record of the user identified by <paramref name="userId"/>, when the record belongs to that user and still holds the
|
||||
/// version it was read with.
|
||||
/// </summary>
|
||||
/// <param name="data">The play record whose editable values are applied to the stored record.</param>
|
||||
/// <param name="userId">The Id of the user the play record must belong to.</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 update, or an error.</returns>
|
||||
public async Task<Result<Updated>> UpdateForUserAsync(MusicPlayRecordEntity data, Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
// The user is part of both the tracked and the stored lookup, so a future caller can never update a record that belongs to another
|
||||
// user merely by knowing its Id.
|
||||
MusicPlayRecordEntity? foundPlayRecord = _luminaDbContext.MusicPlayRecords.Local
|
||||
.FirstOrDefault(playRecord => playRecord.Id == data.Id && playRecord.UserId == userId)
|
||||
?? await _luminaDbContext.MusicPlayRecords
|
||||
.FirstOrDefaultAsync(playRecord => playRecord.Id == data.Id && playRecord.UserId == userId, cancellationToken).ConfigureAwait(false);
|
||||
if (foundPlayRecord is null)
|
||||
return DomainErrors.MusicPlayHistory.MusicPlayRecordNotFound;
|
||||
|
||||
// A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing, and a
|
||||
// concurrent stop or complete that read the same version could then fail for a report that changed no data.
|
||||
bool hasEditableChanges = foundPlayRecord.Status != data.Status ||
|
||||
foundPlayRecord.LastPositionMilliseconds != data.LastPositionMilliseconds ||
|
||||
foundPlayRecord.ListenedDurationMilliseconds != data.ListenedDurationMilliseconds ||
|
||||
foundPlayRecord.EndedOnUtc != data.EndedOnUtc;
|
||||
if (!hasEditableChanges)
|
||||
return Result.Updated;
|
||||
|
||||
// The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
|
||||
// The version is captured before the copy and incremented after it, so the update is only applied when the row still holds the
|
||||
// version the report read; a later progress report can therefore never overwrite a completed or stopped play.
|
||||
Guid storedUserId = foundPlayRecord.UserId;
|
||||
Guid trackId = foundPlayRecord.TrackId;
|
||||
Guid libraryId = foundPlayRecord.LibraryId;
|
||||
Guid albumId = foundPlayRecord.AlbumId;
|
||||
Guid artistId = foundPlayRecord.ArtistId;
|
||||
long version = foundPlayRecord.Version;
|
||||
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundPlayRecord, data);
|
||||
foundPlayRecord.UserId = storedUserId;
|
||||
foundPlayRecord.TrackId = trackId;
|
||||
foundPlayRecord.LibraryId = libraryId;
|
||||
foundPlayRecord.AlbumId = albumId;
|
||||
foundPlayRecord.ArtistId = artistId;
|
||||
foundPlayRecord.Version = version + 1;
|
||||
return Result.Updated;
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,7 @@ public class LuminaDbContext : DbContext
|
||||
public virtual DbSet<ScheduledJobEntity> ScheduledJobs { get; set; } = null!;
|
||||
public virtual DbSet<ScheduledJobExecutionEntity> ScheduledJobExecutions { get; set; } = null!;
|
||||
public virtual DbSet<SchedulerDisplayPreferencesEntity> SchedulerDisplayPreferences { get; set; } = null!;
|
||||
public virtual DbSet<MusicPlayRecordEntity> MusicPlayRecords { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
|
||||
@@ -64,6 +64,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
private IThemeRepository? _themeRepository;
|
||||
private IUserRepository? _userRepository;
|
||||
private IUserSettingsRepository? _userSettingsRepository;
|
||||
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the permission repository.
|
||||
@@ -374,6 +375,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the music play record repository.
|
||||
/// </summary>
|
||||
public IMusicPlayRecordRepository MusicPlayRecordRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_musicPlayRecordRepository ??= new MusicPlayRecordRepository(_luminaDbContext);
|
||||
return _musicPlayRecordRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
@@ -395,13 +408,28 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
await _luminaDbContext.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
|
||||
return Result.Success;
|
||||
}
|
||||
// A concurrency conflict means that another request changed the same row after this request read it. It is an expected persistence
|
||||
// conflict, so it is reported as a failure result instead of bubbling up as an unhandled exception.
|
||||
catch (DbUpdateConcurrencyException)
|
||||
{
|
||||
return Errors.Persistence.ConcurrencyConflict;
|
||||
}
|
||||
// A unique constraint violation is an expected persistence conflict, so it is reported as a failure result instead of bubbling up
|
||||
// as an unhandled exception and being turned into a generic internal server error. Any other exception is unexpected and is left
|
||||
// to propagate to the centralized exception handling middleware.
|
||||
// as an unhandled exception and being turned into a generic internal server error.
|
||||
catch (DbUpdateException exception) when (IsUniqueConstraintViolation(exception))
|
||||
{
|
||||
return Errors.Persistence.UniqueConstraintViolation;
|
||||
}
|
||||
// SQLite reports a busy or locked database when another writer holds the lock. It is a concurrent write conflict, not an unexpected
|
||||
// server failure, so it is reported the same way as an optimistic concurrency conflict.
|
||||
catch (DbUpdateException exception) when (IsSqliteConcurrencyConflict(exception))
|
||||
{
|
||||
return Errors.Persistence.ConcurrencyConflict;
|
||||
}
|
||||
catch (SqliteException exception) when (IsSqliteBusyOrLocked(exception))
|
||||
{
|
||||
return Errors.Persistence.ConcurrencyConflict;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -416,6 +444,26 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
&& sqliteException.SqliteExtendedErrorCode == 2067; // SQLITE_CONSTRAINT_UNIQUE
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided <paramref name="exception"/> was caused by a SQLite write conflict.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> if the exception was caused by a busy or locked database, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsSqliteConcurrencyConflict(DbUpdateException exception)
|
||||
{
|
||||
return exception.InnerException is SqliteException sqliteException && IsSqliteBusyOrLocked(sqliteException);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the provided <paramref name="exception"/> reports a busy or locked SQLite database.
|
||||
/// </summary>
|
||||
/// <param name="exception">The exception to inspect.</param>
|
||||
/// <returns><see langword="true"/> if the database is busy or locked, <see langword="false"/> otherwise.</returns>
|
||||
private static bool IsSqliteBusyOrLocked(SqliteException exception)
|
||||
{
|
||||
return exception.SqliteErrorCode is 5 or 6; // SQLITE_BUSY, SQLITE_LOCKED
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Detaches all the entities tracked by the unit of work, freeing the memory they occupy.
|
||||
/// </summary>
|
||||
|
||||
@@ -11,6 +11,15 @@ public static partial class Errors
|
||||
{
|
||||
public static class MusicPlayHistory
|
||||
{
|
||||
public static Error MusicPlayRecordNotFound => Error.NotFound(description: nameof(MusicPlayRecordNotFound));
|
||||
public static Error MusicPlayRecordAlreadyExists => Error.Conflict(description: nameof(MusicPlayRecordAlreadyExists));
|
||||
public static Error PlayRecordIdCannotBeEmpty => Error.Validation(description: nameof(PlayRecordIdCannotBeEmpty));
|
||||
public static Error PlaybackPositionCannotBeNull => Error.Validation(description: nameof(PlaybackPositionCannotBeNull));
|
||||
public static Error PlaybackPositionMustBeNonNegative => Error.Validation(description: nameof(PlaybackPositionMustBeNonNegative));
|
||||
public static Error PlaybackPositionIsOutOfRange => Error.Validation(description: nameof(PlaybackPositionIsOutOfRange));
|
||||
public static Error ListenedDurationCannotBeNull => Error.Validation(description: nameof(ListenedDurationCannotBeNull));
|
||||
public static Error ListenedDurationMustBeNonNegative => Error.Validation(description: nameof(ListenedDurationMustBeNonNegative));
|
||||
public static Error ListenedDurationIsOutOfRange => Error.Validation(description: nameof(ListenedDurationIsOutOfRange));
|
||||
public static Error PlayIsNotInProgress => Error.Conflict(description: nameof(PlayIsNotInProgress));
|
||||
public static Error ListenedDurationCannotDecrease => Error.Validation(description: nameof(ListenedDurationCannotDecrease));
|
||||
public static Error InProgressPlayCannotHaveEndTime => Error.Validation(description: nameof(InProgressPlayCannotHaveEndTime));
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of the music play history routes of the API.
|
||||
/// </summary>
|
||||
public static partial class ApiRoutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Routes for the music play history of the current user.
|
||||
/// </summary>
|
||||
public static class PlayHistory
|
||||
{
|
||||
public const string START_PLAY = "/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/plays";
|
||||
public const string GET_PLAY = "/users/me/music-play-history/plays/{playRecordId}";
|
||||
public const string REPORT_PLAY_PROGRESS = "/users/me/music-play-history/plays/{playRecordId}/progress";
|
||||
public const string COMPLETE_PLAY = "/users/me/music-play-history/plays/{playRecordId}/complete";
|
||||
public const string STOP_PLAY = "/users/me/music-play-history/plays/{playRecordId}/stop";
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.CompletePlay;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.CompletePlay;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}/complete</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class CompletePlayEndpoint : BaseEndpoint<CompletePlayRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<CompletePlayCommand, Result<Updated>> _completePlayCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompletePlayEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="completePlayCommandHandler">Injected service for handling complete play commands.</param>
|
||||
public CompletePlayEndpoint(ICommandHandler<CompletePlayCommand, Result<Updated>> completePlayCommandHandler)
|
||||
{
|
||||
_completePlayCommandHandler = completePlayCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.PlayHistory.COMPLETE_PLAY);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports that a play of a track by the current user reached its end.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the last position and the listened duration.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(CompletePlayRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take the unique identifier from the route.
|
||||
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
|
||||
Result<Updated> result = await _completePlayCommandHandler.HandleAsync(request.ToCommand(playRecordId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.CompletePlay;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="CompletePlayEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class CompletePlayEndpointSummary : Summary<CompletePlayEndpoint, CompletePlayRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompletePlayEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public CompletePlayEndpointSummary()
|
||||
{
|
||||
Summary = "Reports that a play of a track by the current user reached its end.";
|
||||
Description = "Reports that a play of a track by the current user reached its end, together with the last position and the listened duration. Only an in-progress play of the current user can be completed, and the listened duration can never decrease. The reports are stored so that the play history, statistics and recommendations can be built from them.";
|
||||
|
||||
ExampleRequest = new CompletePlayRequest(
|
||||
PositionInSeconds: 354,
|
||||
ListenedDurationInSeconds: 354
|
||||
);
|
||||
|
||||
RequestParam(request => request.PositionInSeconds, "The last position reported by the player, in seconds. Required.");
|
||||
RequestParam(request => request.ListenedDurationInSeconds, "The duration the user listened to, in seconds. Required.");
|
||||
|
||||
Response(200, "The completion of the play was reported.", example: new { });
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "MusicPlayRecordNotFound",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(409, "The request failed because the play is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "PlayIsNotInProgress",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "ConcurrencyConflict",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/complete",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"PlayRecordIdCannotBeEmpty",
|
||||
"PlaybackPositionCannotBeNull",
|
||||
"PlaybackPositionMustBeNonNegative",
|
||||
"PlaybackPositionIsOutOfRange",
|
||||
"ListenedDurationCannotBeNull",
|
||||
"ListenedDurationMustBeNonNegative",
|
||||
"ListenedDurationIsOutOfRange",
|
||||
"ListenedDurationCannotDecrease"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetPlayRecord;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetPlayRecord;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class GetPlayRecordEndpoint : BaseEndpoint<EmptyRequest, IResult>
|
||||
{
|
||||
private readonly IQueryHandler<GetPlayRecordQuery, Result<PlayRecordResponse>> _getPlayRecordQueryHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlayRecordEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="getPlayRecordQueryHandler">Injected service for handling get play record queries.</param>
|
||||
public GetPlayRecordEndpoint(IQueryHandler<GetPlayRecordQuery, Result<PlayRecordResponse>> getPlayRecordQueryHandler)
|
||||
{
|
||||
_getPlayRecordQueryHandler = getPlayRecordQueryHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(Http.GET);
|
||||
Routes(ApiRoutes.PlayHistory.GET_PLAY);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a recorded play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// The play record belongs to the authenticated user, so no intermediary may store any response of this route, including its problem
|
||||
// responses, and every response varies by the bearer token that authorized it.
|
||||
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
|
||||
HttpContext.Response.Headers["Vary"] = "Authorization";
|
||||
// Take the unique identifier from the route.
|
||||
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
|
||||
Result<PlayRecordResponse> result = await _getPlayRecordQueryHandler.HandleAsync(new GetPlayRecordQuery(playRecordId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetPlayRecord;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="GetPlayRecordEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetPlayRecordEndpointSummary : Summary<GetPlayRecordEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetPlayRecordEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public GetPlayRecordEndpointSummary()
|
||||
{
|
||||
Summary = "Retrieves a recorded play of a track by the current user.";
|
||||
Description = "Retrieves the play record identified by the route, when it belongs to the current user. The record carries the last reported position, the listened duration and whether the play is in progress, completed or stopped. It never carries a queue, a current index, a repeat or shuffle state, or a playback session.";
|
||||
|
||||
ResponseParam<PlayRecordResponse>(r => r.Id, "The Id of the play record.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.TrackId, "The Id of the track that was played.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.LibraryId, "The Id of the media library that contains the track.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.AlbumId, "The Id of the album that contains the track.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.ArtistId, "The Id of the artist that produced the track.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.Status, "The state of the recorded play.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.LastPositionInSeconds, "The last position reported by the player, in seconds.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.ListenedDurationInSeconds, "The duration the user has listened to, in seconds.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.StartedOnUtc, "The date and time when the play started.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.EndedOnUtc, "The date and time when the play completed or stopped, if it has ended.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.UpdatedOnUtc, "The date and time when the play record was last updated, if applicable.");
|
||||
|
||||
Response(200, "The play record is returned.",
|
||||
example: new PlayRecordResponse(
|
||||
Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"),
|
||||
TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
|
||||
AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
|
||||
ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
|
||||
Status: PlaybackRecordStatus.Stopped,
|
||||
LastPositionInSeconds: 92.5,
|
||||
ListenedDurationInSeconds: 92.5,
|
||||
StartedOnUtc: new DateTime(2026, 10, 19, 12, 0, 0, DateTimeKind.Utc),
|
||||
EndedOnUtc: new DateTime(2026, 10, 19, 12, 1, 32, 500, DateTimeKind.Utc),
|
||||
UpdatedOnUtc: new DateTime(2026, 10, 19, 12, 1, 32, 500, DateTimeKind.Utc)
|
||||
)
|
||||
);
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "MusicPlayRecordNotFound",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"PlayRecordIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.ReportPlayProgress;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.ReportPlayProgress;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}/progress</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class ReportPlayProgressEndpoint : BaseEndpoint<ReportPlayProgressRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<ReportPlayProgressCommand, Result<Updated>> _reportPlayProgressCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportPlayProgressEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="reportPlayProgressCommandHandler">Injected service for handling report play progress commands.</param>
|
||||
public ReportPlayProgressEndpoint(ICommandHandler<ReportPlayProgressCommand, Result<Updated>> reportPlayProgressCommandHandler)
|
||||
{
|
||||
_reportPlayProgressCommandHandler = reportPlayProgressCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.PlayHistory.REPORT_PLAY_PROGRESS);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports the progress of a play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the last position and the listened duration.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(ReportPlayProgressRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take the unique identifier from the route.
|
||||
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
|
||||
Result<Updated> result = await _reportPlayProgressCommandHandler.HandleAsync(request.ToCommand(playRecordId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.ReportPlayProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="ReportPlayProgressEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ReportPlayProgressEndpointSummary : Summary<ReportPlayProgressEndpoint, ReportPlayProgressRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportPlayProgressEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public ReportPlayProgressEndpointSummary()
|
||||
{
|
||||
Summary = "Reports the progress of a play of a track by the current user.";
|
||||
Description = "Reports the last position and the listened duration of a play of a track by the current user. Only an in-progress play of the current user can be progressed, and the listened duration can never decrease. The reports are stored so that the play history, statistics and recommendations can be built from them.";
|
||||
|
||||
ExampleRequest = new ReportPlayProgressRequest(
|
||||
PositionInSeconds: 92.5,
|
||||
ListenedDurationInSeconds: 92.5
|
||||
);
|
||||
|
||||
RequestParam(request => request.PositionInSeconds, "The last position reported by the player, in seconds. Required.");
|
||||
RequestParam(request => request.ListenedDurationInSeconds, "The duration the user has listened to, in seconds. Required.");
|
||||
|
||||
Response(200, "The progress of the play was reported.", example: new { });
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "MusicPlayRecordNotFound",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(409, "The request failed because the play is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "PlayIsNotInProgress",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "ConcurrencyConflict",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/progress",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"PlayRecordIdCannotBeEmpty",
|
||||
"PlaybackPositionCannotBeNull",
|
||||
"PlaybackPositionMustBeNonNegative",
|
||||
"PlaybackPositionIsOutOfRange",
|
||||
"ListenedDurationCannotBeNull",
|
||||
"ListenedDurationMustBeNonNegative",
|
||||
"ListenedDurationIsOutOfRange",
|
||||
"ListenedDurationCannotDecrease"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StartPlay;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.StartPlay;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/plays</c> route.
|
||||
/// </summary>
|
||||
public class StartPlayEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<StartPlayCommand, Result<PlayRecordResponse>> _startPlayCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartPlayEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="startPlayCommandHandler">Injected service for handling start play commands.</param>
|
||||
public StartPlayEndpoint(ICommandHandler<StartPlayCommand, Result<PlayRecordResponse>> startPlayCommandHandler)
|
||||
{
|
||||
_startPlayCommandHandler = startPlayCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.POST);
|
||||
Routes(ApiRoutes.PlayHistory.START_PLAY);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Records the start of a play of a track by the current user.
|
||||
/// </summary>
|
||||
/// <param name="request">The request object.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take the unique identifiers from the route, so that they cannot be replaced by values posted in a body.
|
||||
string? libraryId = HttpContext.Request.RouteValues["libraryId"]?.ToString();
|
||||
string? artistId = HttpContext.Request.RouteValues["artistId"]?.ToString();
|
||||
string? albumId = HttpContext.Request.RouteValues["albumId"]?.ToString();
|
||||
string? trackId = HttpContext.Request.RouteValues["trackId"]?.ToString();
|
||||
Result<PlayRecordResponse> result = await _startPlayCommandHandler
|
||||
.HandleAsync(new StartPlayCommand(libraryId, artistId, albumId, trackId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.Playback;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.StartPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="StartPlayEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StartPlayEndpointSummary : Summary<StartPlayEndpoint, EmptyRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartPlayEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public StartPlayEndpointSummary()
|
||||
{
|
||||
Summary = "Records the start of a play of a track by the current user.";
|
||||
Description = "Records the start of a play of a track by the current user, so that the play history, statistics and recommendations can be built from it. The track must belong to the named library, album and artist. The play record is returned with its identifier, which the player uses to report its progress, completion or stop. The play record belongs to the current user, and it never stores a queue, a current index, a repeat or shuffle state, or a playback session.";
|
||||
|
||||
ResponseParam<PlayRecordResponse>(r => r.Id, "The Id of the play record.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.TrackId, "The Id of the track that was played.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.LibraryId, "The Id of the media library that contains the track.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.AlbumId, "The Id of the album that contains the track.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.ArtistId, "The Id of the artist that produced the track.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.Status, "The state of the recorded play.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.LastPositionInSeconds, "The last position reported by the player, in seconds.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.ListenedDurationInSeconds, "The duration the user has listened to, in seconds.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.StartedOnUtc, "The date and time when the play started.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.EndedOnUtc, "The date and time when the play completed or stopped, if it has ended.");
|
||||
ResponseParam<PlayRecordResponse>(r => r.UpdatedOnUtc, "The date and time when the play record was last updated, if applicable.");
|
||||
|
||||
Response(200, "The play was recorded and its play record is returned.",
|
||||
example: new PlayRecordResponse(
|
||||
Id: Guid.Parse("2c1b0a9f-8e7d-4c6b-5a4f-3e2d1c0b9a8f"),
|
||||
TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
|
||||
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
|
||||
AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
|
||||
ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
|
||||
Status: PlaybackRecordStatus.InProgress,
|
||||
LastPositionInSeconds: 0,
|
||||
ListenedDurationInSeconds: 0,
|
||||
StartedOnUtc: new DateTime(2026, 10, 19, 12, 0, 0, DateTimeKind.Utc),
|
||||
EndedOnUtc: null,
|
||||
UpdatedOnUtc: null
|
||||
)
|
||||
);
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(403, "The request failed because the user making the request is not an Admin, or the owner of the media library.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
|
||||
title = "General.Unauthorized",
|
||||
status = 403,
|
||||
detail = "NotAuthorized",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the album or the track does not exist, or they do not belong to the library, artist and album named by the request.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "AlbumNotFound",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "TrackNotFound",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = "/api/v1/libraries/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a/artists/d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/tracks/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/plays",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"LibraryIdCannotBeEmpty",
|
||||
"ArtistIdCannotBeEmpty",
|
||||
"AlbumIdCannotBeEmpty",
|
||||
"TrackIdCannotBeEmpty"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Commands.StopPlay;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Common;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.StopPlay;
|
||||
|
||||
/// <summary>
|
||||
/// API endpoint for the <c>/users/me/music-play-history/plays/{playRecordId}/stop</c> route.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Uses "me" because it is always for the currently authenticated user.
|
||||
/// </remarks>
|
||||
public class StopPlayEndpoint : BaseEndpoint<StopPlayRequest, IResult>
|
||||
{
|
||||
private readonly ICommandHandler<StopPlayCommand, Result<Updated>> _stopPlayCommandHandler;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopPlayEndpoint"/> class.
|
||||
/// </summary>
|
||||
/// <param name="stopPlayCommandHandler">Injected service for handling stop play commands.</param>
|
||||
public StopPlayEndpoint(ICommandHandler<StopPlayCommand, Result<Updated>> stopPlayCommandHandler)
|
||||
{
|
||||
_stopPlayCommandHandler = stopPlayCommandHandler;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configures the API endpoint.
|
||||
/// </summary>
|
||||
public override void Configure()
|
||||
{
|
||||
Verbs(FastEndpoints.Http.PUT);
|
||||
Routes(ApiRoutes.PlayHistory.STOP_PLAY);
|
||||
Version(1);
|
||||
DontCatchExceptions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reports that a play of a track by the current user stopped before the track completed.
|
||||
/// </summary>
|
||||
/// <param name="request">The request containing the last position and the listened duration.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
public override async Task<IResult> ExecuteAsync(StopPlayRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
// Take the unique identifier from the route.
|
||||
string? playRecordId = HttpContext.Request.RouteValues["playRecordId"]?.ToString();
|
||||
Result<Updated> result = await _stopPlayCommandHandler.HandleAsync(request.ToCommand(playRecordId), cancellationToken).ConfigureAwait(false);
|
||||
return result.Match(success => TypedResults.Ok(success), Problem);
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.StopPlay;
|
||||
|
||||
/// <summary>
|
||||
/// Class used for providing a textual description for the <see cref="StopPlayEndpoint"/> API endpoint, for OpenAPI.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StopPlayEndpointSummary : Summary<StopPlayEndpoint, StopPlayRequest>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopPlayEndpointSummary"/> class.
|
||||
/// </summary>
|
||||
public StopPlayEndpointSummary()
|
||||
{
|
||||
Summary = "Reports that a play of a track by the current user stopped before the track completed.";
|
||||
Description = "Reports that a play of a track by the current user stopped before the track completed, together with the last position and the listened duration. Only an in-progress play of the current user can be stopped, and the listened duration can never decrease. The reports are stored so that the play history, statistics and recommendations can be built from them.";
|
||||
|
||||
ExampleRequest = new StopPlayRequest(
|
||||
PositionInSeconds: 92.5,
|
||||
ListenedDurationInSeconds: 92.5
|
||||
);
|
||||
|
||||
RequestParam(request => request.PositionInSeconds, "The last position reported by the player, in seconds. Required.");
|
||||
RequestParam(request => request.ListenedDurationInSeconds, "The duration the user listened to, in seconds. Required.");
|
||||
|
||||
Response(200, "The stop of the play was reported.", example: new { });
|
||||
|
||||
Response(401, "Authentication required.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "Authentication failed",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token has expired",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc7235#section-3.1",
|
||||
status = 401,
|
||||
title = "Unauthorized",
|
||||
detail = "The token is invalid",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(404, "The request failed because the play record does not exist, or it does not belong to the current user.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.5",
|
||||
title = "General.NotFound",
|
||||
status = 404,
|
||||
detail = "MusicPlayRecordNotFound",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
|
||||
traceId = "00-57d15dadd702dbd4aeb5dc9b7cee68ee-9330237dbb2ce0e5-00"
|
||||
}
|
||||
);
|
||||
|
||||
Response(409, "The request failed because the play is not in progress anymore, or because another report changed it after this request read it.", "application/problem+json",
|
||||
example: new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "PlayIsNotInProgress",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
},
|
||||
new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
|
||||
title = "General.Conflict",
|
||||
status = 409,
|
||||
detail = "ConcurrencyConflict",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
|
||||
traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
Response(422, "The request did not pass validation checks.", "application/problem+json",
|
||||
example: new
|
||||
{
|
||||
type = "https://tools.ietf.org/html/rfc4918#section-11.2",
|
||||
title = "General.Validation",
|
||||
status = 422,
|
||||
detail = "OneOrMoreValidationErrorsOccurred",
|
||||
instance = $"/api/v1/users/me/music-play-history/plays/{Guid.NewGuid()}/stop",
|
||||
errors = new Dictionary<string, string[]>
|
||||
{
|
||||
{
|
||||
"General.Validation", new[]
|
||||
{
|
||||
"PlayRecordIdCannotBeEmpty",
|
||||
"PlaybackPositionCannotBeNull",
|
||||
"PlaybackPositionMustBeNonNegative",
|
||||
"PlaybackPositionIsOutOfRange",
|
||||
"ListenedDurationCannotBeNull",
|
||||
"ListenedDurationMustBeNonNegative",
|
||||
"ListenedDurationIsOutOfRange",
|
||||
"ListenedDurationCannotDecrease"
|
||||
}
|
||||
}
|
||||
},
|
||||
traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "music-library", "music-libr
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
..\docs\technical\api\library\audio-library\music-library\Api.Albums.md = ..\docs\technical\api\library\audio-library\music-library\Api.Albums.md
|
||||
..\docs\technical\api\library\audio-library\music-library\Api.Artists.md = ..\docs\technical\api\library\audio-library\music-library\Api.Artists.md
|
||||
..\docs\technical\api\library\audio-library\music-library\Api.PlayHistory.md = ..\docs\technical\api\library\audio-library\music-library\Api.PlayHistory.md
|
||||
..\docs\technical\api\library\audio-library\music-library\Api.Tracks.md = ..\docs\technical\api\library\audio-library\music-library\Api.Tracks.md
|
||||
EndProjectSection
|
||||
EndProject
|
||||
@@ -294,6 +295,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tracks", "tracks", "{B1B657
|
||||
..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http = ..\docs\technical\requests\library\audio-library\music-library\tracks\UpdateTrack.http
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "play-history", "play-history", "{9402C854-E845-4F86-BECB-F708E0C7CB2E}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
..\docs\technical\requests\library\audio-library\music-library\play-history\CompletePlay.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\CompletePlay.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\play-history\GetPlayRecord.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\GetPlayRecord.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\play-history\ReportPlayProgress.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\ReportPlayProgress.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\play-history\StartPlay.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\StartPlay.http
|
||||
..\docs\technical\requests\library\audio-library\music-library\play-history\StopPlay.http = ..\docs\technical\requests\library\audio-library\music-library\play-history\StopPlay.http
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "management", "management", "{FDED0D4B-3FB6-42CA-AC73-76038F9DDF5E}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
..\docs\technical\requests\library\management\AddLibrary.http = ..\docs\technical\requests\library\management\AddLibrary.http
|
||||
@@ -1413,6 +1423,7 @@ Global
|
||||
{B4DF8E8D-C245-4E7C-B85B-B52935EDA93B} = {A65199DD-543E-4C18-A16A-215BD34962A5}
|
||||
{F3818697-E304-491D-8BF3-4DAA1733B5F5} = {A65199DD-543E-4C18-A16A-215BD34962A5}
|
||||
{B1B657B1-60DC-4E22-89D2-6212154D6BA8} = {A65199DD-543E-4C18-A16A-215BD34962A5}
|
||||
{9402C854-E845-4F86-BECB-F708E0C7CB2E} = {A65199DD-543E-4C18-A16A-215BD34962A5}
|
||||
{FDED0D4B-3FB6-42CA-AC73-76038F9DDF5E} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09}
|
||||
{61824D19-B08C-45C6-95F8-716B5FDA183C} = {38048ADA-6830-4575-BDA6-C6D77E6D3E09}
|
||||
{0C975F46-8A47-48EC-91A0-2B222032C043} = {61824D19-B08C-45C6-95F8-716B5FDA183C}
|
||||
|
||||
+2
-1
@@ -48,7 +48,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
|
||||
// Assert
|
||||
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
|
||||
Assert.Equal(62, tableNames.Length);
|
||||
Assert.Equal(63, tableNames.Length);
|
||||
Assert.Contains("Books", tableNames);
|
||||
Assert.Contains("Users", tableNames);
|
||||
Assert.Contains("UserSettings", tableNames);
|
||||
@@ -108,6 +108,7 @@ public class LuminaDbContextTests : IDisposable
|
||||
Assert.Contains("AlbumContributors", tableNames);
|
||||
Assert.Contains("MusicArtwork", tableNames);
|
||||
Assert.Contains("MusicLibraryScanItemMetadata", tableNames);
|
||||
Assert.Contains("MusicPlayRecords", tableNames);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
|
||||
Reference in new issue
Block a user