implement more robust command api and login
improve web console command response reliability and consistency
This commit is contained in:
parent
dd3ebf6b34
commit
23a33ba489
@ -72,6 +72,7 @@ namespace IW4MAdmin.Application
|
|||||||
private readonly IServiceProvider _serviceProvider;
|
private readonly IServiceProvider _serviceProvider;
|
||||||
private readonly ChangeHistoryService _changeHistoryService;
|
private readonly ChangeHistoryService _changeHistoryService;
|
||||||
private readonly ApplicationConfiguration _appConfig;
|
private readonly ApplicationConfiguration _appConfig;
|
||||||
|
public ConcurrentDictionary<long, GameEvent> ProcessingEvents { get; } = new ConcurrentDictionary<long, GameEvent>();
|
||||||
|
|
||||||
public ApplicationManager(ILogger<ApplicationManager> logger, IMiddlewareActionHandler actionHandler, IEnumerable<IManagerCommand> commands,
|
public ApplicationManager(ILogger<ApplicationManager> logger, IMiddlewareActionHandler actionHandler, IEnumerable<IManagerCommand> commands,
|
||||||
ITranslationLookup translationLookup, IConfigurationHandler<CommandConfiguration> commandConfiguration,
|
ITranslationLookup translationLookup, IConfigurationHandler<CommandConfiguration> commandConfiguration,
|
||||||
@ -115,6 +116,8 @@ namespace IW4MAdmin.Application
|
|||||||
|
|
||||||
public async Task ExecuteEvent(GameEvent newEvent)
|
public async Task ExecuteEvent(GameEvent newEvent)
|
||||||
{
|
{
|
||||||
|
ProcessingEvents.TryAdd(newEvent.Id, newEvent);
|
||||||
|
|
||||||
// the event has failed already
|
// the event has failed already
|
||||||
if (newEvent.Failed)
|
if (newEvent.Failed)
|
||||||
{
|
{
|
||||||
@ -175,6 +178,29 @@ namespace IW4MAdmin.Application
|
|||||||
}
|
}
|
||||||
|
|
||||||
skip:
|
skip:
|
||||||
|
if (newEvent.Type == EventType.Command && newEvent.ImpersonationOrigin == null)
|
||||||
|
{
|
||||||
|
var correlatedEvents =
|
||||||
|
ProcessingEvents.Values.Where(ev =>
|
||||||
|
ev.CorrelationId == newEvent.CorrelationId && ev.Id != newEvent.Id)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
await Task.WhenAll(correlatedEvents.Select(ev =>
|
||||||
|
ev.WaitAsync(Utilities.DefaultCommandTimeout, CancellationToken)));
|
||||||
|
newEvent.Output.AddRange(correlatedEvents.SelectMany(ev => ev.Output));
|
||||||
|
|
||||||
|
foreach (var correlatedEvent in correlatedEvents)
|
||||||
|
{
|
||||||
|
ProcessingEvents.Remove(correlatedEvent.Id, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// we don't want to remove events that are correlated to command
|
||||||
|
if (ProcessingEvents.Values.Count(gameEvent => gameEvent.CorrelationId == newEvent.CorrelationId) == 1)
|
||||||
|
{
|
||||||
|
ProcessingEvents.Remove(newEvent.Id, out _);
|
||||||
|
}
|
||||||
|
|
||||||
// tell anyone waiting for the output that we're done
|
// tell anyone waiting for the output that we're done
|
||||||
newEvent.Complete();
|
newEvent.Complete();
|
||||||
OnGameEventExecuted?.Invoke(this, newEvent);
|
OnGameEventExecuted?.Invoke(this, newEvent);
|
||||||
|
@ -154,7 +154,8 @@ namespace IW4MAdmin
|
|||||||
|
|
||||||
catch (CommandException e)
|
catch (CommandException e)
|
||||||
{
|
{
|
||||||
ServerLogger.LogWarning(e, "Error validating command from event {@event}", E);
|
ServerLogger.LogWarning(e, "Error validating command from event {@event}",
|
||||||
|
new { E.Type, E.Data, E.Message, E.Subtype, E.IsRemote, E.CorrelationId });
|
||||||
E.FailReason = GameEvent.EventFailReason.Invalid;
|
E.FailReason = GameEvent.EventFailReason.Invalid;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -25,40 +25,39 @@ namespace SharedLibraryCore.Commands
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task ExecuteAsync(GameEvent E)
|
public override async Task ExecuteAsync(GameEvent gameEvent)
|
||||||
{
|
{
|
||||||
if (E.IsTargetingSelf())
|
if (gameEvent.IsTargetingSelf())
|
||||||
{
|
{
|
||||||
E.Origin.Tell(_translationLookup["COMMANDS_RUN_AS_SELF"]);
|
gameEvent.Origin.Tell(_translationLookup["COMMANDS_RUN_AS_SELF"]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!E.CanPerformActionOnTarget())
|
if (!gameEvent.CanPerformActionOnTarget())
|
||||||
{
|
{
|
||||||
E.Origin.Tell(_translationLookup["COMMANDS_RUN_AS_FAIL_PERM"]);
|
gameEvent.Origin.Tell(_translationLookup["COMMANDS_RUN_AS_FAIL_PERM"]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
string cmd = $"{Utilities.CommandPrefix}{E.Data}";
|
var cmd = $"{Utilities.CommandPrefix}{gameEvent.Data}";
|
||||||
var impersonatedCommandEvent = new GameEvent()
|
var impersonatedCommandEvent = new GameEvent()
|
||||||
{
|
{
|
||||||
Type = GameEvent.EventType.Command,
|
Type = GameEvent.EventType.Command,
|
||||||
Origin = E.Target,
|
Origin = gameEvent.Target,
|
||||||
ImpersonationOrigin = E.Origin,
|
ImpersonationOrigin = gameEvent.Origin,
|
||||||
Message = cmd,
|
Message = cmd,
|
||||||
Data = cmd,
|
Data = cmd,
|
||||||
Owner = E.Owner
|
Owner = gameEvent.Owner,
|
||||||
|
CorrelationId = gameEvent.CorrelationId
|
||||||
};
|
};
|
||||||
E.Owner.Manager.AddEvent(impersonatedCommandEvent);
|
gameEvent.Owner.Manager.AddEvent(impersonatedCommandEvent);
|
||||||
|
|
||||||
var result = await impersonatedCommandEvent.WaitAsync(Utilities.DefaultCommandTimeout, E.Owner.Manager.CancellationToken);
|
var result = await impersonatedCommandEvent.WaitAsync(Utilities.DefaultCommandTimeout, gameEvent.Owner.Manager.CancellationToken);
|
||||||
var response = E.Owner.CommandResult.Where(c => c.ClientId == E.Target.ClientId).ToList();
|
|
||||||
|
|
||||||
// remove the added command response
|
// remove the added command response
|
||||||
for (int i = 0; i < response.Count; i++)
|
foreach (var output in result.Output)
|
||||||
{
|
{
|
||||||
E.Origin.Tell(_translationLookup["COMMANDS_RUN_AS_SUCCESS"].FormatExt(response[i].Response));
|
gameEvent.Origin.Tell(_translationLookup["COMMANDS_RUN_AS_SUCCESS"].FormatExt(output));
|
||||||
E.Owner.CommandResult.Remove(response[i]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
using SharedLibraryCore.Database.Models;
|
using SharedLibraryCore.Database.Models;
|
||||||
using SharedLibraryCore.Events;
|
using SharedLibraryCore.Events;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@ -247,6 +248,8 @@ namespace SharedLibraryCore
|
|||||||
public long Id { get; private set; }
|
public long Id { get; private set; }
|
||||||
public EventFailReason FailReason { get; set; }
|
public EventFailReason FailReason { get; set; }
|
||||||
public bool Failed => FailReason != EventFailReason.None;
|
public bool Failed => FailReason != EventFailReason.None;
|
||||||
|
public Guid CorrelationId { get; set; } = Guid.NewGuid();
|
||||||
|
public List<string> Output { get; set; } = new List<string>();
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Indicates if the event should block until it is complete
|
/// Indicates if the event should block until it is complete
|
||||||
@ -280,7 +283,7 @@ namespace SharedLibraryCore
|
|||||||
{
|
{
|
||||||
using(LogContext.PushProperty("Server", Owner?.ToString()))
|
using(LogContext.PushProperty("Server", Owner?.ToString()))
|
||||||
{
|
{
|
||||||
Utilities.DefaultLogger.LogError("Waiting for event to complete timed out {@eventData}", new { Event = this, Message, Origin = Origin.ToString(), Target = Target.ToString()});
|
Utilities.DefaultLogger.LogError("Waiting for event to complete timed out {@eventData}", new { Event = this, Message, Origin = Origin?.ToString(), Target = Target?.ToString()});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,6 +6,7 @@ using SharedLibraryCore.Database.Models;
|
|||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
|
||||||
namespace SharedLibraryCore.Interfaces
|
namespace SharedLibraryCore.Interfaces
|
||||||
@ -86,5 +87,6 @@ namespace SharedLibraryCore.Interfaces
|
|||||||
/// event executed when event has finished executing
|
/// event executed when event has finished executing
|
||||||
/// </summary>
|
/// </summary>
|
||||||
event EventHandler<GameEvent> OnGameEventExecuted;
|
event EventHandler<GameEvent> OnGameEventExecuted;
|
||||||
|
ConcurrentDictionary<long, GameEvent> ProcessingEvents { get; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -133,7 +133,7 @@ namespace SharedLibraryCore.Database.Models
|
|||||||
/// send a message directly to the connected client
|
/// send a message directly to the connected client
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="message">message content to send to client</param>
|
/// <param name="message">message content to send to client</param>
|
||||||
public GameEvent Tell(String message)
|
public GameEvent Tell(string message)
|
||||||
{
|
{
|
||||||
var e = new GameEvent()
|
var e = new GameEvent()
|
||||||
{
|
{
|
||||||
@ -141,9 +141,13 @@ namespace SharedLibraryCore.Database.Models
|
|||||||
Target = this,
|
Target = this,
|
||||||
Owner = CurrentServer,
|
Owner = CurrentServer,
|
||||||
Type = GameEvent.EventType.Tell,
|
Type = GameEvent.EventType.Tell,
|
||||||
Data = message
|
Data = message,
|
||||||
|
CorrelationId = CurrentServer.Manager.ProcessingEvents.Values
|
||||||
|
.FirstOrDefault(ev => ev.Type == GameEvent.EventType.Command && (ev.Origin?.ClientId == ClientId || ev.ImpersonationOrigin?.ClientId == ClientId))?.CorrelationId ?? Guid.NewGuid()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
e.Output.Add(message.StripColors());
|
||||||
|
|
||||||
CurrentServer?.Manager.AddEvent(e);
|
CurrentServer?.Manager.AddEvent(e);
|
||||||
return e;
|
return e;
|
||||||
}
|
}
|
||||||
|
@ -172,22 +172,6 @@ namespace SharedLibraryCore
|
|||||||
Console.WriteLine(message.StripColors());
|
Console.WriteLine(message.StripColors());
|
||||||
Console.ForegroundColor = ConsoleColor.Gray;
|
Console.ForegroundColor = ConsoleColor.Gray;
|
||||||
}
|
}
|
||||||
|
|
||||||
// prevent this from queueing up too many command responses
|
|
||||||
if (CommandResult.Count > 15)
|
|
||||||
{
|
|
||||||
CommandResult.RemoveAt(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// it was a remote command so we need to add it to the command result queue
|
|
||||||
if (target.ClientNumber < 0)
|
|
||||||
{
|
|
||||||
CommandResult.Add(new CommandResponseInfo()
|
|
||||||
{
|
|
||||||
Response = message.StripColors(),
|
|
||||||
ClientId = target.ClientId
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -347,8 +331,5 @@ namespace SharedLibraryCore
|
|||||||
// only here for performance
|
// only here for performance
|
||||||
private readonly bool CustomSayEnabled;
|
private readonly bool CustomSayEnabled;
|
||||||
private readonly string CustomSayName;
|
private readonly string CustomSayName;
|
||||||
|
|
||||||
//Remote
|
|
||||||
public IList<CommandResponseInfo> CommandResult = new List<CommandResponseInfo>();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -3,9 +3,15 @@ using Microsoft.AspNetCore.Mvc;
|
|||||||
using SharedLibraryCore.Dtos;
|
using SharedLibraryCore.Dtos;
|
||||||
using SharedLibraryCore.Interfaces;
|
using SharedLibraryCore.Interfaces;
|
||||||
using System;
|
using System;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Security.Claims;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Authentication;
|
||||||
|
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SharedLibraryCore;
|
||||||
|
using SharedLibraryCore.Services;
|
||||||
using WebfrontCore.Controllers.API.Dtos;
|
using WebfrontCore.Controllers.API.Dtos;
|
||||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||||
|
|
||||||
@ -15,29 +21,34 @@ namespace WebfrontCore.Controllers.API
|
|||||||
/// api controller for client operations
|
/// api controller for client operations
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[ApiController]
|
[ApiController]
|
||||||
[Route("api/client")]
|
[Route("api/[controller]")]
|
||||||
public class ClientController : ControllerBase
|
public class ClientController : BaseController
|
||||||
{
|
{
|
||||||
private readonly IResourceQueryHelper<FindClientRequest, FindClientResult> _clientQueryHelper;
|
private readonly IResourceQueryHelper<FindClientRequest, FindClientResult> _clientQueryHelper;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
private readonly ClientService _clientService;
|
||||||
|
|
||||||
public ClientController(ILogger<ClientController> logger, IResourceQueryHelper<FindClientRequest, FindClientResult> clientQueryHelper)
|
public ClientController(ILogger<ClientController> logger,
|
||||||
|
IResourceQueryHelper<FindClientRequest, FindClientResult> clientQueryHelper,
|
||||||
|
ClientService clientService, IManager manager) : base(manager)
|
||||||
{
|
{
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_clientQueryHelper = clientQueryHelper;
|
_clientQueryHelper = clientQueryHelper;
|
||||||
|
_clientService = clientService;
|
||||||
}
|
}
|
||||||
|
|
||||||
[HttpGet("find")]
|
[HttpGet("find")]
|
||||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||||
public async Task<IActionResult> FindAsync([FromQuery]FindClientRequest request)
|
public async Task<IActionResult> FindAsync([FromQuery] FindClientRequest request)
|
||||||
{
|
{
|
||||||
if (!ModelState.IsValid)
|
if (!ModelState.IsValid)
|
||||||
{
|
{
|
||||||
return BadRequest(new ErrorResponse()
|
return BadRequest(new ErrorResponse()
|
||||||
{
|
{
|
||||||
Messages = ModelState.Values.SelectMany(_value => _value.Errors.Select(_error => _error.ErrorMessage)).ToArray()
|
Messages = ModelState.Values
|
||||||
|
.SelectMany(_value => _value.Errors.Select(_error => _error.ErrorMessage)).ToArray()
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -58,9 +69,84 @@ namespace WebfrontCore.Controllers.API
|
|||||||
|
|
||||||
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse()
|
return StatusCode(StatusCodes.Status500InternalServerError, new ErrorResponse()
|
||||||
{
|
{
|
||||||
Messages = new[] { e.Message }
|
Messages = new[] {e.Message}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
[HttpPost("{clientId:int}/login")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||||
|
public async Task<IActionResult> LoginAsync([FromRoute] int clientId,
|
||||||
|
[FromBody, Required] PasswordRequest request)
|
||||||
|
{
|
||||||
|
if (clientId == 0)
|
||||||
|
{
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpContext.Request.Cookies.TryGetValue(".AspNetCore.Cookies", out var cookie);
|
||||||
|
|
||||||
|
if (Authorized)
|
||||||
|
{
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var privilegedClient = await _clientService.GetClientForLogin(clientId);
|
||||||
|
var loginSuccess = false;
|
||||||
|
|
||||||
|
if (!Authorized)
|
||||||
|
{
|
||||||
|
loginSuccess =
|
||||||
|
Manager.TokenAuthenticator.AuthorizeToken(privilegedClient.NetworkId, request.Password) ||
|
||||||
|
(await Task.FromResult(SharedLibraryCore.Helpers.Hashing.Hash(request.Password,
|
||||||
|
privilegedClient.PasswordSalt)))[0] == privilegedClient.Password;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loginSuccess)
|
||||||
|
{
|
||||||
|
var claims = new[]
|
||||||
|
{
|
||||||
|
new Claim(ClaimTypes.NameIdentifier, privilegedClient.Name),
|
||||||
|
new Claim(ClaimTypes.Role, privilegedClient.Level.ToString()),
|
||||||
|
new Claim(ClaimTypes.Sid, privilegedClient.ClientId.ToString()),
|
||||||
|
new Claim(ClaimTypes.PrimarySid, privilegedClient.NetworkId.ToString("X"))
|
||||||
|
};
|
||||||
|
|
||||||
|
var claimsIdentity = new ClaimsIdentity(claims, "login");
|
||||||
|
var claimsPrinciple = new ClaimsPrincipal(claimsIdentity);
|
||||||
|
await SignInAsync(claimsPrinciple);
|
||||||
|
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{clientId:int}/logout")]
|
||||||
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||||
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
||||||
|
public async Task<IActionResult> LogoutAsync()
|
||||||
|
{
|
||||||
|
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
|
||||||
|
|
||||||
|
return Ok();
|
||||||
|
}
|
||||||
|
|
||||||
|
public class PasswordRequest
|
||||||
|
{
|
||||||
|
public string Password { get; set; }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
7
WebfrontCore/Controllers/API/Models/CommandRequest.cs
Normal file
7
WebfrontCore/Controllers/API/Models/CommandRequest.cs
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
namespace WebfrontCore.Controllers.API.Models
|
||||||
|
{
|
||||||
|
public class CommandRequest
|
||||||
|
{
|
||||||
|
public string Command { get; set; }
|
||||||
|
}
|
||||||
|
}
|
93
WebfrontCore/Controllers/API/Server.cs
Normal file
93
WebfrontCore/Controllers/API/Server.cs
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using SharedLibraryCore;
|
||||||
|
using SharedLibraryCore.Interfaces;
|
||||||
|
using WebfrontCore.Controllers.API.Models;
|
||||||
|
|
||||||
|
namespace WebfrontCore.Controllers.API
|
||||||
|
{
|
||||||
|
[ApiController]
|
||||||
|
[Route("api/[controller]")]
|
||||||
|
public class Server : BaseController
|
||||||
|
{
|
||||||
|
|
||||||
|
public Server(IManager manager) : base(manager)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet]
|
||||||
|
public IActionResult Index()
|
||||||
|
{
|
||||||
|
return new JsonResult(Manager.GetServers().Select(server => new
|
||||||
|
{
|
||||||
|
Id = server.EndPoint,
|
||||||
|
server.Hostname,
|
||||||
|
server.IP,
|
||||||
|
server.Port
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("{id}")]
|
||||||
|
public IActionResult GetServerById(string id)
|
||||||
|
{
|
||||||
|
var foundServer = Manager.GetServers().FirstOrDefault(server => server.EndPoint == long.Parse(id));
|
||||||
|
|
||||||
|
if (foundServer == null)
|
||||||
|
{
|
||||||
|
return new NotFoundResult();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new JsonResult(new
|
||||||
|
{
|
||||||
|
Id = foundServer.EndPoint,
|
||||||
|
foundServer.Hostname,
|
||||||
|
foundServer.IP,
|
||||||
|
foundServer.Port
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpPost("{id}/execute")]
|
||||||
|
public async Task<IActionResult> ExecuteCommandForServer(string id, [FromBody] CommandRequest commandRequest)
|
||||||
|
{
|
||||||
|
if (!Authorized)
|
||||||
|
{
|
||||||
|
return Unauthorized();
|
||||||
|
}
|
||||||
|
|
||||||
|
var foundServer = Manager.GetServers().FirstOrDefault(server => server.EndPoint == long.Parse(id));
|
||||||
|
|
||||||
|
if (foundServer == null)
|
||||||
|
{
|
||||||
|
return new BadRequestObjectResult($"No server with id '{id}' was found");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (string.IsNullOrEmpty(commandRequest.Command))
|
||||||
|
{
|
||||||
|
return new BadRequestObjectResult("Command cannot be empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
var start = DateTime.Now;
|
||||||
|
Client.CurrentServer = foundServer;
|
||||||
|
|
||||||
|
var commandEvent = new GameEvent()
|
||||||
|
{
|
||||||
|
Type = GameEvent.EventType.Command,
|
||||||
|
Owner = foundServer,
|
||||||
|
Origin = Client,
|
||||||
|
Data = commandRequest.Command,
|
||||||
|
Extra = commandRequest.Command
|
||||||
|
};
|
||||||
|
|
||||||
|
Manager.AddEvent(commandEvent);
|
||||||
|
var completedEvent = await commandEvent.WaitAsync(Utilities.DefaultCommandTimeout, foundServer.Manager.CancellationToken);
|
||||||
|
|
||||||
|
return new JsonResult(new
|
||||||
|
{
|
||||||
|
ExecutionTimeMs = Math.Round((DateTime.Now - start).TotalMilliseconds, 0),
|
||||||
|
completedEvent.Output
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -52,8 +52,10 @@ namespace WebfrontCore.Controllers
|
|||||||
var remoteEvent = new GameEvent()
|
var remoteEvent = new GameEvent()
|
||||||
{
|
{
|
||||||
Type = GameEvent.EventType.Command,
|
Type = GameEvent.EventType.Command,
|
||||||
Data = command.StartsWith(_appconfig.CommandPrefix) || command.StartsWith(_appconfig.BroadcastCommandPrefix) ?
|
Data = command.StartsWith(_appconfig.CommandPrefix) ||
|
||||||
command : $"{_appconfig.CommandPrefix}{command}",
|
command.StartsWith(_appconfig.BroadcastCommandPrefix)
|
||||||
|
? command
|
||||||
|
: $"{_appconfig.CommandPrefix}{command}",
|
||||||
Origin = client,
|
Origin = client,
|
||||||
Owner = server,
|
Owner = server,
|
||||||
IsRemote = true
|
IsRemote = true
|
||||||
@ -65,7 +67,8 @@ namespace WebfrontCore.Controllers
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
// wait for the event to process
|
// wait for the event to process
|
||||||
var completedEvent = await remoteEvent.WaitAsync(Utilities.DefaultCommandTimeout, server.Manager.CancellationToken);
|
var completedEvent =
|
||||||
|
await remoteEvent.WaitAsync(Utilities.DefaultCommandTimeout, server.Manager.CancellationToken);
|
||||||
|
|
||||||
if (completedEvent.FailReason == GameEvent.EventFailReason.Timeout)
|
if (completedEvent.FailReason == GameEvent.EventFailReason.Timeout)
|
||||||
{
|
{
|
||||||
@ -81,13 +84,11 @@ namespace WebfrontCore.Controllers
|
|||||||
|
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
response = response = server.CommandResult.Where(c => c.ClientId == client.ClientId).ToArray();
|
response = completedEvent.Output.Select(output => new CommandResponseInfo()
|
||||||
}
|
{
|
||||||
|
Response = output,
|
||||||
// remove the added command response
|
ClientId = client.ClientId
|
||||||
for (int i = 0; i < response?.Length; i++)
|
}).ToArray();
|
||||||
{
|
|
||||||
server.CommandResult.Remove(response[i]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -115,6 +115,7 @@ namespace WebfrontCore
|
|||||||
services.AddSingleton(Program.ApplicationServiceProvider.GetService<IEnumerable<IManagerCommand>>());
|
services.AddSingleton(Program.ApplicationServiceProvider.GetService<IEnumerable<IManagerCommand>>());
|
||||||
services.AddSingleton(Program.ApplicationServiceProvider.GetService<IMetaService>());
|
services.AddSingleton(Program.ApplicationServiceProvider.GetService<IMetaService>());
|
||||||
services.AddSingleton(Program.ApplicationServiceProvider.GetService<ApplicationConfiguration>());
|
services.AddSingleton(Program.ApplicationServiceProvider.GetService<ApplicationConfiguration>());
|
||||||
|
services.AddSingleton(Program.ApplicationServiceProvider.GetRequiredService<ClientService>());
|
||||||
}
|
}
|
||||||
|
|
||||||
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user