sledgemapper/Sledgemapper.Api/Handlers/NewOverlayCommandHandler.cs
Michele Scandura db41143312
All checks were successful
continuous-integration/drone/push Build is passing
fixed load and overlay flow, missing sync
2021-09-17 11:42:36 +01:00

60 lines
2.1 KiB
C#

using MediatR;
using Sledgemapper.Api.Commands;
using Sledgemapper.Api.Notifications;
using Sledgemapper.Api.Infrastructure.Data;
using Sledgemapper.Shared.Entities;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System;
using Microsoft.EntityFrameworkCore;
namespace Sledgemapper.Api.Handlers
{
public class NewOverlayCommandHandler : IRequestHandler<NewOverlayCommand, bool>
{
private readonly SledgemapperDbContext _dbcontext;
private readonly IMediator _mediator;
public NewOverlayCommandHandler(IMediator mediator, SledgemapperDbContext dbcontext) { _dbcontext = dbcontext; _mediator = mediator; }
public async Task<bool> Handle(NewOverlayCommand command, CancellationToken cancellationToken)
{
var user = await _dbcontext.Users.FindAsync(command.UserId);
_dbcontext.Attach(user);
var campaign = await _dbcontext
.Campaigns
.Where(campaign => campaign.CampaignId == command.Campaign)
.Include(c => c.InvitedUsers)
.Include(c => c.Maps)
.Include(c => c.Owner)
.Where(campaign => campaign.OwnerId == command.UserId || campaign.InvitedUsers.Contains(user)).FirstAsync();
var maps = campaign.Maps.Any(s => s.SessionId == command.SessionId);
if (!maps)
{
throw new Exception("Unauthorized");
}
var jsonString = JsonSerializer.Serialize(command.Overlay);
var session = _dbcontext.Sessions.First(m => m.SessionId == command.SessionId);
_dbcontext.MapLogs.Add(new Models.MapLog
{
Operation = "N",
SessionId = session.SessionId,
Type = "O",
Timestamp = command.Timestamp,
Object = jsonString,
UserId = command.UserId,
});
await _dbcontext.SaveChangesAsync();
await _mediator.Publish(new NewOverlayNotification(session, command.Overlay, command.UserId));
return true;
}
}
}