mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 05:11:10 +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,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>
|
||||
|
||||
Reference in new issue
Block a user