Adds the media consumption lifecycle commands and repository wiring

This commit is contained in:
BinaryAlley committed 2026-10-24 17:07:31 +03:00
1 parent 2ffacb5360
commit bde7ee4b1f
30 files changed
+1962 -28

No files matched your search

@@ -0,0 +1,127 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="MediaConsumptionRecordEntity"/> entity.
/// </summary>
public class MediaConsumptionRecordConfiguration : IEntityTypeConfiguration<MediaConsumptionRecordEntity>
{
/// <summary>
/// Configures the <see cref="MediaConsumptionRecordEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<MediaConsumptionRecordEntity> builder)
{
builder.ToTable("MediaConsumptionRecords");
builder.HasKey(record => record.Id);
builder.Property(record => record.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
// A consumption record belongs to the user that started it, and it is removed with that user.
builder.HasOne<UserEntity>()
.WithMany()
.HasForeignKey(record => record.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.Property(record => record.UserId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(record => record.LibraryId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(record => record.MediaItemId)
.IsRequired()
.HasColumnOrder(3);
builder.Property(record => record.MediaKind)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(4);
builder.Property(record => record.Status)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(5);
builder.Property(record => record.StartedOnUtc)
.IsRequired()
.HasColumnOrder(6);
builder.Property(record => record.LastActivityOnUtc)
.IsRequired()
.HasColumnOrder(7);
builder.Property(record => record.EndedOnUtc)
.HasColumnOrder(8);
builder.Property(record => record.ConsumedDurationMilliseconds)
.IsRequired()
.HasColumnOrder(9);
builder.Property(record => record.LastPositionKind)
.HasConversion<string>()
.HasMaxLength(20)
.IsRequired(false)
.HasColumnOrder(10);
builder.Property(record => record.LastPositionTimeOffsetMilliseconds)
.HasColumnOrder(11);
builder.Property(record => record.LastPositionLocation)
.HasMaxLength(4096)
.HasColumnOrder(12);
builder.Property(record => record.LastProgressFraction)
.IsRequired()
.HasColumnOrder(13);
builder.Property(record => record.ConsecutivePagesRead)
.IsRequired()
.HasDefaultValue(0)
.HasColumnOrder(14);
// 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 session that another report already completed or stopped.
builder.Property(record => record.Version)
.IsRequired()
.IsConcurrencyToken()
.HasColumnOrder(15);
// Audit.
builder.Property(record => record.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(16);
builder.Property(record => record.CreatedBy)
.IsRequired()
.HasColumnOrder(17);
builder.Property(record => record.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(18);
builder.Property(record => record.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(19);
// The referenced media item is kept by kind and Id only, without a foreign key: one table serves every media kind, so no single table
// can be referenced, and a session survives the deletion of the item it references.
// Enables listing the history of a user from the most recent activity, optionally restricted to one media kind and item.
builder.HasIndex(record => new { record.UserId, record.MediaKind, record.MediaItemId, record.LastActivityOnUtc });
// Enables the statistics of a user restricted by media kind and date range.
builder.HasIndex(record => new { record.UserId, record.MediaKind, record.StartedOnUtc });
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
#endregion
namespace Lumina.DataAccess.Common.Configuration;
/// <summary>
/// Configures the entity mapping for the <see cref="MediaResumePointEntity"/> entity.
/// </summary>
public class MediaResumePointConfiguration : IEntityTypeConfiguration<MediaResumePointEntity>
{
/// <summary>
/// Configures the <see cref="MediaResumePointEntity"/> entity.
/// </summary>
/// <param name="builder">The builder to be used to configure the entity.</param>
public void Configure(EntityTypeBuilder<MediaResumePointEntity> builder)
{
builder.ToTable("MediaResumePoints");
builder.HasKey(resumePoint => resumePoint.Id);
builder.Property(resumePoint => resumePoint.Id)
.ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
.HasColumnOrder(0);
// A resume point belongs to the user that owns it, and it is removed with that user.
builder.HasOne<UserEntity>()
.WithMany()
.HasForeignKey(resumePoint => resumePoint.UserId)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
builder.Property(resumePoint => resumePoint.UserId)
.IsRequired()
.HasColumnOrder(1);
builder.Property(resumePoint => resumePoint.LibraryId)
.IsRequired()
.HasColumnOrder(2);
builder.Property(resumePoint => resumePoint.MediaKind)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(3);
builder.Property(resumePoint => resumePoint.MediaItemId)
.IsRequired()
.HasColumnOrder(4);
builder.Property(resumePoint => resumePoint.LastPositionKind)
.IsRequired()
.HasConversion<string>()
.HasMaxLength(20)
.HasColumnOrder(5);
builder.Property(resumePoint => resumePoint.LastPositionTimeOffsetMilliseconds)
.HasColumnOrder(6);
builder.Property(resumePoint => resumePoint.LastPositionLocation)
.HasMaxLength(4096)
.HasColumnOrder(7);
builder.Property(resumePoint => resumePoint.LastProgressFraction)
.IsRequired()
.HasColumnOrder(8);
builder.Property(resumePoint => resumePoint.LastConsumedOnUtc)
.IsRequired()
.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 resume point that another report already advanced.
builder.Property(resumePoint => resumePoint.Version)
.IsRequired()
.IsConcurrencyToken()
.HasColumnOrder(10);
// Audit.
builder.Property(resumePoint => resumePoint.CreatedOnUtc)
.IsRequired()
.HasColumnOrder(11);
builder.Property(resumePoint => resumePoint.CreatedBy)
.IsRequired()
.HasColumnOrder(12);
builder.Property(resumePoint => resumePoint.UpdatedOnUtc)
.HasDefaultValue(null)
.HasColumnOrder(13);
builder.Property(resumePoint => resumePoint.UpdatedBy)
.HasDefaultValue(null)
.HasColumnOrder(14);
// The referenced media item is kept by kind and Id only, without a foreign key: one table serves every media kind, so no single table
// can be referenced, and a resume point survives the deletion of the item it references.
// The unique index makes the storage medium the owner of the "one resume point per user and item" invariant.
builder.HasIndex(resumePoint => new { resumePoint.UserId, resumePoint.MediaKind, resumePoint.MediaItemId })
.IsUnique();
}
}
@@ -0,0 +1,167 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MediaConsumption;
/// <summary>
/// Repository for media consumption records.
/// </summary>
/// <remarks>
/// Records are always read, updated, and deleted scoped to their owner. The media item they reference is kept by kind and Id only, so a deleted media item leaves the record and its statistics intact.
/// </remarks>
internal sealed class MediaConsumptionRecordRepository : IMediaConsumptionRecordRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="MediaConsumptionRecordRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public MediaConsumptionRecordRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Adds a new consumption record.
/// </summary>
/// <param name="data">The consumption 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 Task<Result<Created>> InsertAsync(MediaConsumptionRecordEntity data, CancellationToken cancellationToken)
{
// The handler creates a new session with a newly generated Id, so this always adds a row.
_luminaDbContext.MediaConsumptionRecords.Add(data);
return Task.FromResult<Result<Created>>(Result.Created);
}
/// <summary>
/// Gets the consumption 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 consumption record to get.</param>
/// <param name="userId">The Id of the user the consumption 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 consumption 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<MediaConsumptionRecordEntity?>> 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<MediaConsumptionRecordEntity> query = _luminaDbContext.MediaConsumptionRecords
.Where(record => record.Id == id && record.UserId == userId);
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Updates the consumption 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 consumption record whose editable values are applied to the stored record. Its owner must match <paramref name="userId"/>.</param>
/// <param name="userId">The Id of the user the consumption record must belong to. It is authoritative for locating the stored record; the owner carried by <paramref name="data"/> is not used to select it.</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(MediaConsumptionRecordEntity data, Guid userId, CancellationToken cancellationToken)
{
// The user is part of both the tracked and the stored lookup, so a caller can never update a record that belongs to another user merely by knowing its Id.
MediaConsumptionRecordEntity? foundRecord = _luminaDbContext.MediaConsumptionRecords.Local
.FirstOrDefault(record => record.Id == data.Id && record.UserId == userId)
?? await _luminaDbContext.MediaConsumptionRecords
.FirstOrDefaultAsync(record => record.Id == data.Id && record.UserId == userId, cancellationToken).ConfigureAwait(false);
if (foundRecord is null)
return DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
// 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.
if (!HasEditableChanges(foundRecord, data))
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.
Guid storedUserId = foundRecord.UserId;
Guid libraryId = foundRecord.LibraryId;
Guid mediaItemId = foundRecord.MediaItemId;
MediaKind mediaKind = foundRecord.MediaKind;
DateTime startedOnUtc = foundRecord.StartedOnUtc;
long version = foundRecord.Version;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundRecord, data);
foundRecord.UserId = storedUserId;
foundRecord.LibraryId = libraryId;
foundRecord.MediaItemId = mediaItemId;
foundRecord.MediaKind = mediaKind;
foundRecord.StartedOnUtc = startedOnUtc;
foundRecord.Version = version + 1;
return Result.Updated;
}
/// <summary>
/// Deletes the consumption record identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>. A record that does not exist is not an error.
/// </summary>
/// <param name="id">The Id of the consumption record to delete.</param>
/// <param name="userId">The Id of the user the consumption 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 deletion, or an error.</returns>
public async Task<Result<Deleted>> DeleteForUserAsync(Guid id, Guid userId, CancellationToken cancellationToken)
{
// A handler may already have loaded the same record in this unit of work, so the tracked instance is preferred over materializing a second copy.
MediaConsumptionRecordEntity? record = _luminaDbContext.MediaConsumptionRecords.Local
.FirstOrDefault(trackedRecord => trackedRecord.Id == id && trackedRecord.UserId == userId)
?? await _luminaDbContext.MediaConsumptionRecords
.FirstOrDefaultAsync(foundRecord => foundRecord.Id == id && foundRecord.UserId == userId, cancellationToken).ConfigureAwait(false);
if (record is null)
return Result.Deleted;
_luminaDbContext.MediaConsumptionRecords.Remove(record);
return Result.Deleted;
}
/// <summary>
/// Deletes every consumption record of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose consumption records are deleted.</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 deletion, or an error.</returns>
public async Task<Result<Deleted>> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken)
{
List<MediaConsumptionRecordEntity> records = await _luminaDbContext.MediaConsumptionRecords
.Where(record => record.UserId == userId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (records.Count > 0)
_luminaDbContext.MediaConsumptionRecords.RemoveRange(records);
return Result.Deleted;
}
/// <summary>
/// Determines whether <paramref name="incoming"/> carries values that differ from the stored <paramref name="stored"/> record.
/// </summary>
/// <param name="stored">The record currently stored in the persistence medium.</param>
/// <param name="incoming">The record carrying the values to apply.</param>
/// <returns><see langword="true"/> if an editable value changed, <see langword="false"/> otherwise.</returns>
private static bool HasEditableChanges(MediaConsumptionRecordEntity stored, MediaConsumptionRecordEntity incoming)
{
return stored.Status != incoming.Status ||
stored.LastActivityOnUtc != incoming.LastActivityOnUtc ||
stored.EndedOnUtc != incoming.EndedOnUtc ||
stored.ConsumedDurationMilliseconds != incoming.ConsumedDurationMilliseconds ||
stored.LastPositionKind != incoming.LastPositionKind ||
stored.LastPositionTimeOffsetMilliseconds != incoming.LastPositionTimeOffsetMilliseconds ||
stored.LastPositionLocation != incoming.LastPositionLocation ||
stored.LastProgressFraction != incoming.LastProgressFraction ||
stored.ConsecutivePagesRead != incoming.ConsecutivePagesRead;
}
}
@@ -0,0 +1,179 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
using Lumina.DataAccess.Common.Persistence;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.DataAccess.Core.Repositories.MediaConsumption;
/// <summary>
/// Repository for media resume points.
/// </summary>
/// <remarks>
/// The business key of a resume point is the user, the media kind, and the media item. The unique index on those columns makes the storage
/// medium the owner of the "one resume point per user and item" invariant, and an upsert updates the existing row instead of inserting a second one.
/// </remarks>
internal sealed class MediaResumePointRepository : IMediaResumePointRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="MediaResumePointRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public MediaResumePointRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets the resume point of the user identified by <paramref name="userId"/> for the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if it exists.
/// </summary>
/// <param name="userId">The Id of the user the resume point must belong to.</param>
/// <param name="mediaKind">The kind of the media item to resume.</param>
/// <param name="mediaItemId">The Id of the media item to resume.</param>
/// <param name="shouldTrackEntities">Whether the retrieved resume point 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 resume point of the user for the media item, <see langword="null"/> when no such resume point exists, or an error.
/// </returns>
public async Task<Result<MediaResumePointEntity?>> GetForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, 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 resume point that belongs to another user in the first place.
IQueryable<MediaResumePointEntity> query = _luminaDbContext.MediaResumePoints
.Where(resumePoint => resumePoint.UserId == userId &&
resumePoint.MediaKind == mediaKind &&
resumePoint.MediaItemId == mediaItemId);
if (!shouldTrackEntities)
query = query.AsNoTracking();
return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Saves the resume point of the user identified by <paramref name="userId"/>, inserting it when it does not exist and updating it otherwise. The
/// business key of the resume point, made of the user, the media kind, and the media item, is preserved.
/// </summary>
/// <param name="data">The resume point whose values are saved. Its owner must match <paramref name="userId"/>.</param>
/// <param name="userId">The Id of the user the resume point must belong to. It is authoritative for locating the stored resume point and for the owner of a new one; the owner carried by <paramref name="data"/> is not used to select it.</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 save, or an error.</returns>
public async Task<Result<Updated>> UpsertForUserAsync(MediaResumePointEntity data, Guid userId, CancellationToken cancellationToken)
{
// The business key is located in the tracked entities first, so an upsert of a resume point that this unit of work already loaded updates that instance instead of materializing a second copy.
MediaResumePointEntity? foundResumePoint = _luminaDbContext.MediaResumePoints.Local
.FirstOrDefault(resumePoint => resumePoint.UserId == userId &&
resumePoint.MediaKind == data.MediaKind &&
resumePoint.MediaItemId == data.MediaItemId)
?? await _luminaDbContext.MediaResumePoints
.FirstOrDefaultAsync(resumePoint => resumePoint.UserId == userId &&
resumePoint.MediaKind == data.MediaKind &&
resumePoint.MediaItemId == data.MediaItemId, cancellationToken).ConfigureAwait(false);
if (foundResumePoint is null)
{
// The user argument is authoritative for the owner of the new row, not the owner carried by the caller.
data.UserId = userId;
_luminaDbContext.MediaResumePoints.Add(data);
return Result.Updated;
}
// A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing.
if (!HasEditableChanges(foundResumePoint, data))
return Result.Updated;
// The business key is never reassigned by an upsert. 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.
Guid storedUserId = foundResumePoint.UserId;
MediaKind mediaKind = foundResumePoint.MediaKind;
Guid mediaItemId = foundResumePoint.MediaItemId;
long version = foundResumePoint.Version;
EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundResumePoint, data);
foundResumePoint.UserId = storedUserId;
foundResumePoint.MediaKind = mediaKind;
foundResumePoint.MediaItemId = mediaItemId;
foundResumePoint.Version = version + 1;
return Result.Updated;
}
/// <summary>
/// Deletes the resume point of the user identified by <paramref name="userId"/> for the media item identified by <paramref name="mediaKind"/> and
/// <paramref name="mediaItemId"/>. A resume point that does not exist is not an error.
/// </summary>
/// <param name="userId">The Id of the user the resume point must belong to.</param>
/// <param name="mediaKind">The kind of the media item to resume.</param>
/// <param name="mediaItemId">The Id of the media item to resume.</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 deletion, or an error.</returns>
public async Task<Result<Deleted>> DeleteForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken)
{
MediaResumePointEntity? resumePoint = _luminaDbContext.MediaResumePoints.Local
.FirstOrDefault(trackedResumePoint => trackedResumePoint.UserId == userId &&
trackedResumePoint.MediaKind == mediaKind &&
trackedResumePoint.MediaItemId == mediaItemId)
?? await _luminaDbContext.MediaResumePoints
.FirstOrDefaultAsync(foundResumePoint => foundResumePoint.UserId == userId &&
foundResumePoint.MediaKind == mediaKind &&
foundResumePoint.MediaItemId == mediaItemId, cancellationToken).ConfigureAwait(false);
if (resumePoint is null)
return Result.Deleted;
_luminaDbContext.MediaResumePoints.Remove(resumePoint);
return Result.Deleted;
}
/// <summary>
/// Deletes every resume point of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose resume points are deleted.</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 deletion, or an error.</returns>
public async Task<Result<Deleted>> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken)
{
List<MediaResumePointEntity> resumePoints = await _luminaDbContext.MediaResumePoints
.Where(resumePoint => resumePoint.UserId == userId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (resumePoints.Count > 0)
_luminaDbContext.MediaResumePoints.RemoveRange(resumePoints);
return Result.Deleted;
}
/// <summary>
/// Deletes every resume point of the user identified by <paramref name="userId"/> in the media library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose resume points are deleted.</param>
/// <param name="libraryId">The Id of the media library whose resume points are deleted.</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 deletion, or an error.</returns>
public async Task<Result<Deleted>> DeleteAllForUserInLibraryAsync(Guid userId, Guid libraryId, CancellationToken cancellationToken)
{
List<MediaResumePointEntity> resumePoints = await _luminaDbContext.MediaResumePoints
.Where(resumePoint => resumePoint.UserId == userId && resumePoint.LibraryId == libraryId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
if (resumePoints.Count > 0)
_luminaDbContext.MediaResumePoints.RemoveRange(resumePoints);
return Result.Deleted;
}
/// <summary>
/// Determines whether <paramref name="incoming"/> carries values that differ from the stored <paramref name="stored"/> resume point.
/// </summary>
/// <param name="stored">The resume point currently stored in the persistence medium.</param>
/// <param name="incoming">The resume point carrying the values to apply.</param>
/// <returns><see langword="true"/> if an editable value changed, <see langword="false"/> otherwise.</returns>
private static bool HasEditableChanges(MediaResumePointEntity stored, MediaResumePointEntity incoming)
{
return stored.LibraryId != incoming.LibraryId ||
stored.LastPositionKind != incoming.LastPositionKind ||
stored.LastPositionTimeOffsetMilliseconds != incoming.LastPositionTimeOffsetMilliseconds ||
stored.LastPositionLocation != incoming.LastPositionLocation ||
stored.LastProgressFraction != incoming.LastProgressFraction ||
stored.LastConsumedOnUtc != incoming.LastConsumedOnUtc;
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Favorites;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
@@ -56,6 +57,8 @@ public class LuminaDbContext : DbContext
public virtual DbSet<PlaylistEntity> Playlists { get; set; } = null!;
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
public virtual DbSet<FavoriteEntity> Favorites { get; set; } = null!;
public virtual DbSet<MediaConsumptionRecordEntity> MediaConsumptionRecords { get; set; } = null!;
public virtual DbSet<MediaResumePointEntity> MediaResumePoints { get; set; } = null!;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
@@ -16,6 +17,7 @@ using Lumina.DataAccess.Core.Repositories.Authorization;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Favorites;
using Lumina.DataAccess.Core.Repositories.Libraries;
using Lumina.DataAccess.Core.Repositories.MediaConsumption;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.Playlists;
@@ -71,6 +73,8 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
private IPlaylistRepository? _playlistRepository;
private IFavoriteRepository? _favoriteRepository;
private IMediaConsumptionRecordRepository? _mediaConsumptionRecordRepository;
private IMediaResumePointRepository? _mediaResumePointRepository;
/// <summary>
/// Gets the permission repository.
@@ -417,6 +421,30 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the media consumption record repository.
/// </summary>
public IMediaConsumptionRecordRepository MediaConsumptionRecordRepository
{
get
{
_mediaConsumptionRecordRepository ??= new MediaConsumptionRecordRepository(_luminaDbContext);
return _mediaConsumptionRecordRepository;
}
}
/// <summary>
/// Gets the media resume point repository.
/// </summary>
public IMediaResumePointRepository MediaResumePointRepository
{
get
{
_mediaResumePointRepository ??= new MediaResumePointRepository(_luminaDbContext);
return _mediaResumePointRepository;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary>