sledgemapper/Sledgemapper.Api/Handlers/NewOverlayCommandHandler.cs
Michele Scandura 155cb4ea9a
All checks were successful
continuous-integration/drone/push Build is passing
wiring up map updates
2021-09-16 16:34:44 +01:00

52 lines
2 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 == new Guid(command.Campaign) && campaign.OwnerId == command.UserId).Include(campaign => campaign.Maps).FirstAsync();
var maps = campaign.Maps.Any(s => s.SessionId == int.Parse(command.SessionName));
if (!maps)
{
throw new Exception("Unauthorized");
}
var jsonString = JsonSerializer.Serialize(command.Overlay);
var session = _dbcontext.Sessions.First(m => m.SessionId == int.Parse(command.SessionName));
_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;
}
}
}