2248a2b757
Reviewed-on: #11 Co-authored-by: Marek Jasiński <jasins.marek@gmail.com> Co-committed-by: Marek Jasiński <jasins.marek@gmail.com>
48 lines
1.6 KiB
C#
48 lines
1.6 KiB
C#
using FluentResults;
|
|
using MediatR;
|
|
using Microsoft.AspNetCore.SignalR;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using NexusReader.Application.Commands.Sync;
|
|
using NexusReader.Domain.Entities;
|
|
using NexusReader.Data.Persistence;
|
|
using NexusReader.Infrastructure.RealTime;
|
|
|
|
namespace NexusReader.Infrastructure.Handlers;
|
|
|
|
public class UpdateReadingProgressCommandHandler : IRequestHandler<UpdateReadingProgressCommand, Result>
|
|
{
|
|
private readonly IDbContextFactory<AppDbContext> _dbContextFactory;
|
|
private readonly IHubContext<SyncHub> _hubContext;
|
|
|
|
public UpdateReadingProgressCommandHandler(
|
|
IDbContextFactory<AppDbContext> dbContextFactory,
|
|
IHubContext<SyncHub> hubContext)
|
|
{
|
|
_dbContextFactory = dbContextFactory;
|
|
_hubContext = hubContext;
|
|
}
|
|
|
|
public async Task<Result> Handle(UpdateReadingProgressCommand request, CancellationToken cancellationToken)
|
|
{
|
|
using var context = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
|
var user = await context.Users.FirstOrDefaultAsync(u => u.Id == request.UserId, cancellationToken);
|
|
if (user == null)
|
|
{
|
|
return Result.Fail("User not found.");
|
|
}
|
|
|
|
var now = DateTime.UtcNow;
|
|
user.LastReadPageId = request.PageId;
|
|
user.LastReadAt = now;
|
|
|
|
await context.SaveChangesAsync(cancellationToken);
|
|
|
|
// Broadcast to other devices
|
|
await _hubContext.Clients
|
|
.Group($"User_{request.UserId}")
|
|
.SendAsync("ProgressUpdated", request.PageId, now, cancellationToken);
|
|
|
|
return Result.Ok();
|
|
}
|
|
}
|