Compare commits
15 Commits
2022.02.23
...
2022.03.03
Author | SHA1 | Date | |
---|---|---|---|
59ca399045 | |||
ef70496546 | |||
e6e56d8d14 | |||
55b0caf900 | |||
a4c3f9c2d1 | |||
241aa0a5f6 | |||
ec0f59cdb1 | |||
59d69bd22b | |||
e9c8ead829 | |||
58d48a211e | |||
edf8e03b04 | |||
de2e804b84 | |||
b087d4c8de | |||
bd6c0dd5be | |||
4ace476242 |
@ -92,7 +92,7 @@ namespace IW4MAdmin.Application.Commands
|
||||
|
||||
_logger.LogDebug("Changing map to {Map} and gametype {Gametype}", map, gametype);
|
||||
|
||||
await gameEvent.Owner.SetDvarAsync("g_gametype", gametype);
|
||||
await gameEvent.Owner.SetDvarAsync("g_gametype", gametype, gameEvent.Owner.Manager.CancellationToken);
|
||||
gameEvent.Owner.Broadcast(_translationLookup["COMMANDS_MAP_SUCCESS"].FormatExt(map));
|
||||
await Task.Delay(gameEvent.Owner.Manager.GetApplicationSettings().Configuration().MapChangeDelaySeconds);
|
||||
|
||||
|
@ -67,7 +67,7 @@ namespace IW4MAdmin.Application.IO
|
||||
return Task.FromResult(Enumerable.Empty<GameEvent>());
|
||||
}
|
||||
|
||||
new Thread(() => ReadNetworkData(client)).Start();
|
||||
Task.Run(async () => await ReadNetworkData(client, _token), _token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@ -111,9 +111,9 @@ namespace IW4MAdmin.Application.IO
|
||||
return Task.FromResult((IEnumerable<GameEvent>)events);
|
||||
}
|
||||
|
||||
private void ReadNetworkData(UdpClient client)
|
||||
private async Task ReadNetworkData(UdpClient client, CancellationToken token)
|
||||
{
|
||||
while (!_token.IsCancellationRequested)
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
// get more data
|
||||
IPEndPoint remoteEndpoint = null;
|
||||
@ -127,7 +127,13 @@ namespace IW4MAdmin.Application.IO
|
||||
|
||||
try
|
||||
{
|
||||
bufferedData = client.Receive(ref remoteEndpoint);
|
||||
var result = await client.ReceiveAsync(_token);
|
||||
remoteEndpoint = result.RemoteEndPoint;
|
||||
bufferedData = result.Buffer;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_logger.LogDebug("Stopping network log receive");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
@ -321,7 +321,7 @@ namespace IW4MAdmin
|
||||
|
||||
if (!string.IsNullOrEmpty(CustomSayName))
|
||||
{
|
||||
await this.SetDvarAsync("sv_sayname", CustomSayName);
|
||||
await this.SetDvarAsync("sv_sayname", CustomSayName, Manager.CancellationToken);
|
||||
}
|
||||
|
||||
Throttled = false;
|
||||
@ -783,7 +783,7 @@ namespace IW4MAdmin
|
||||
async Task<List<EFClient>[]> PollPlayersAsync()
|
||||
{
|
||||
var currentClients = GetClientsAsList();
|
||||
var statusResponse = (await this.GetStatusAsync());
|
||||
var statusResponse = await this.GetStatusAsync(Manager.CancellationToken);
|
||||
var polledClients = statusResponse.Clients.AsEnumerable();
|
||||
|
||||
if (Manager.GetApplicationSettings().Configuration().IgnoreBots)
|
||||
@ -1109,7 +1109,7 @@ namespace IW4MAdmin
|
||||
RemoteConnection = RConConnectionFactory.CreateConnection(ResolvedIpEndPoint, Password, RconParser.RConEngine);
|
||||
RemoteConnection.SetConfiguration(RconParser);
|
||||
|
||||
var version = await this.GetMappedDvarValueOrDefaultAsync<string>("version");
|
||||
var version = await this.GetMappedDvarValueOrDefaultAsync<string>("version", token: Manager.CancellationToken);
|
||||
Version = version.Value;
|
||||
GameName = Utilities.GetGame(version.Value ?? RconParser.Version);
|
||||
|
||||
@ -1126,7 +1126,7 @@ namespace IW4MAdmin
|
||||
Version = RconParser.Version;
|
||||
}
|
||||
|
||||
var svRunning = await this.GetMappedDvarValueOrDefaultAsync<string>("sv_running");
|
||||
var svRunning = await this.GetMappedDvarValueOrDefaultAsync<string>("sv_running", token: Manager.CancellationToken);
|
||||
|
||||
if (!string.IsNullOrEmpty(svRunning.Value) && svRunning.Value != "1")
|
||||
{
|
||||
@ -1135,27 +1135,28 @@ namespace IW4MAdmin
|
||||
|
||||
var infoResponse = RconParser.Configuration.CommandPrefixes.RConGetInfo != null ? await this.GetInfoAsync() : null;
|
||||
|
||||
string hostname = (await this.GetMappedDvarValueOrDefaultAsync<string>("sv_hostname", "hostname", infoResponse)).Value;
|
||||
string mapname = (await this.GetMappedDvarValueOrDefaultAsync<string>("mapname", infoResponse: infoResponse)).Value;
|
||||
int maxplayers = (await this.GetMappedDvarValueOrDefaultAsync<int>("sv_maxclients", infoResponse: infoResponse)).Value;
|
||||
string gametype = (await this.GetMappedDvarValueOrDefaultAsync<string>("g_gametype", "gametype", infoResponse)).Value;
|
||||
var basepath = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_basepath");
|
||||
var basegame = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_basegame");
|
||||
var homepath = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_homepath");
|
||||
var game = (await this.GetMappedDvarValueOrDefaultAsync<string>("fs_game", infoResponse: infoResponse));
|
||||
var logfile = await this.GetMappedDvarValueOrDefaultAsync<string>("g_log");
|
||||
var logsync = await this.GetMappedDvarValueOrDefaultAsync<int>("g_logsync");
|
||||
var ip = await this.GetMappedDvarValueOrDefaultAsync<string>("net_ip");
|
||||
var gamePassword = await this.GetMappedDvarValueOrDefaultAsync("g_password", overrideDefault: "");
|
||||
var hostname = (await this.GetMappedDvarValueOrDefaultAsync<string>("sv_hostname", "hostname", infoResponse, token: Manager.CancellationToken)).Value;
|
||||
var mapname = (await this.GetMappedDvarValueOrDefaultAsync<string>("mapname", infoResponse: infoResponse, token: Manager.CancellationToken)).Value;
|
||||
var maxplayers = (await this.GetMappedDvarValueOrDefaultAsync<int>("sv_maxclients", infoResponse: infoResponse, token: Manager.CancellationToken)).Value;
|
||||
var gametype = (await this.GetMappedDvarValueOrDefaultAsync<string>("g_gametype", "gametype", infoResponse, token: Manager.CancellationToken)).Value;
|
||||
var basepath = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_basepath", token: Manager.CancellationToken);
|
||||
var basegame = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_basegame", token: Manager.CancellationToken);
|
||||
var homepath = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_homepath", token: Manager.CancellationToken);
|
||||
var game = await this.GetMappedDvarValueOrDefaultAsync<string>("fs_game", infoResponse: infoResponse, token: Manager.CancellationToken);
|
||||
var logfile = await this.GetMappedDvarValueOrDefaultAsync<string>("g_log", token: Manager.CancellationToken);
|
||||
var logsync = await this.GetMappedDvarValueOrDefaultAsync<int>("g_logsync", token: Manager.CancellationToken);
|
||||
var ip = await this.GetMappedDvarValueOrDefaultAsync<string>("net_ip", token: Manager.CancellationToken);
|
||||
var gamePassword = await this.GetMappedDvarValueOrDefaultAsync("g_password", overrideDefault: "", token: Manager.CancellationToken);
|
||||
|
||||
if (Manager.GetApplicationSettings().Configuration().EnableCustomSayName)
|
||||
{
|
||||
await this.SetDvarAsync("sv_sayname", Manager.GetApplicationSettings().Configuration().CustomSayName);
|
||||
await this.SetDvarAsync("sv_sayname", Manager.GetApplicationSettings().Configuration().CustomSayName,
|
||||
Manager.CancellationToken);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var website = await this.GetMappedDvarValueOrDefaultAsync<string>("_website");
|
||||
var website = await this.GetMappedDvarValueOrDefaultAsync<string>("_website", token: Manager.CancellationToken);
|
||||
|
||||
// this occurs for games that don't give us anything back when
|
||||
// the dvar is not set
|
||||
@ -1201,14 +1202,14 @@ namespace IW4MAdmin
|
||||
|
||||
if (logsync.Value == 0)
|
||||
{
|
||||
await this.SetDvarAsync("g_logsync", 2); // set to 2 for continous in other games, clamps to 1 for IW4
|
||||
await this.SetDvarAsync("g_logsync", 2, Manager.CancellationToken); // set to 2 for continous in other games, clamps to 1 for IW4
|
||||
needsRestart = true;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(logfile.Value))
|
||||
{
|
||||
logfile.Value = "games_mp.log";
|
||||
await this.SetDvarAsync("g_log", logfile.Value);
|
||||
await this.SetDvarAsync("g_log", logfile.Value, Manager.CancellationToken);
|
||||
needsRestart = true;
|
||||
}
|
||||
|
||||
@ -1220,7 +1221,7 @@ namespace IW4MAdmin
|
||||
}
|
||||
|
||||
// this DVAR isn't set until the a map is loaded
|
||||
await this.SetDvarAsync("logfile", 2);
|
||||
await this.SetDvarAsync("logfile", 2, Manager.CancellationToken);
|
||||
}
|
||||
|
||||
CustomCallback = await ScriptLoaded();
|
||||
|
@ -154,6 +154,8 @@ namespace IW4MAdmin.Application
|
||||
Console.WriteLine(e.Message);
|
||||
}
|
||||
|
||||
_serverManager?.Stop();
|
||||
|
||||
Console.WriteLine(exitMessage);
|
||||
await Console.In.ReadAsync(new char[1], 0, 1);
|
||||
return;
|
||||
|
@ -39,7 +39,8 @@ public class
|
||||
PreviousPermissionLevelValue = change.PreviousValue,
|
||||
CurrentPermissionLevelValue = change.CurrentValue,
|
||||
When = change.TimeChanged,
|
||||
ClientId = change.TargetEntityId
|
||||
ClientId = change.TargetEntityId,
|
||||
IsSensitive = true
|
||||
};
|
||||
|
||||
return new ResourceQueryHelperResult<PermissionLevelChangedResponse>
|
||||
|
@ -88,7 +88,7 @@ namespace IW4MAdmin.Application.Migration
|
||||
|
||||
public static void RemoveObsoletePlugins20210322()
|
||||
{
|
||||
var files = new[] {"StatsWeb.dll", "StatsWeb.Views.dll"};
|
||||
var files = new[] {"StatsWeb.dll", "StatsWeb.Views.dll", "IW4ScriptCommands.dll"};
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
|
@ -27,6 +27,7 @@ namespace IW4MAdmin.Application.Misc
|
||||
_serializerOptions = new JsonSerializerOptions
|
||||
{
|
||||
WriteIndented = true,
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
||||
};
|
||||
_serializerOptions.Converters.Add(new JsonStringEnumConverter());
|
||||
_onSaving = new SemaphoreSlim(1, 1);
|
||||
|
@ -7,6 +7,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Data.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@ -77,19 +78,19 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
public string RConEngine { get; set; } = "COD";
|
||||
public bool IsOneLog { get; set; }
|
||||
|
||||
public async Task<string[]> ExecuteCommandAsync(IRConConnection connection, string command)
|
||||
public async Task<string[]> ExecuteCommandAsync(IRConConnection connection, string command, CancellationToken token = default)
|
||||
{
|
||||
var response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, command);
|
||||
var response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, command, token);
|
||||
return response.Where(item => item != Configuration.CommandPrefixes.RConResponse).ToArray();
|
||||
}
|
||||
|
||||
public async Task<Dvar<T>> GetDvarAsync<T>(IRConConnection connection, string dvarName, T fallbackValue = default)
|
||||
public async Task<Dvar<T>> GetDvarAsync<T>(IRConConnection connection, string dvarName, T fallbackValue = default, CancellationToken token = default)
|
||||
{
|
||||
string[] lineSplit;
|
||||
|
||||
try
|
||||
{
|
||||
lineSplit = await connection.SendQueryAsync(StaticHelpers.QueryType.GET_DVAR, dvarName);
|
||||
lineSplit = await connection.SendQueryAsync(StaticHelpers.QueryType.GET_DVAR, dvarName, token);
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -98,10 +99,10 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
throw;
|
||||
}
|
||||
|
||||
lineSplit = new string[0];
|
||||
lineSplit = Array.Empty<string>();
|
||||
}
|
||||
|
||||
string response = string.Join('\n', lineSplit).TrimEnd('\0');
|
||||
var response = string.Join('\n', lineSplit).TrimEnd('\0');
|
||||
var match = Regex.Match(response, Configuration.Dvar.Pattern);
|
||||
|
||||
if (response.Contains("Unknown command") ||
|
||||
@ -109,7 +110,7 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
{
|
||||
if (fallbackValue != null)
|
||||
{
|
||||
return new Dvar<T>()
|
||||
return new Dvar<T>
|
||||
{
|
||||
Name = dvarName,
|
||||
Value = fallbackValue
|
||||
@ -119,17 +120,17 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
throw new DvarException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_DVAR"].FormatExt(dvarName));
|
||||
}
|
||||
|
||||
string value = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarValue]].Value;
|
||||
string defaultValue = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarDefaultValue]].Value;
|
||||
string latchedValue = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarLatchedValue]].Value;
|
||||
var value = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarValue]].Value;
|
||||
var defaultValue = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarDefaultValue]].Value;
|
||||
var latchedValue = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarLatchedValue]].Value;
|
||||
|
||||
string removeTrailingColorCode(string input) => Regex.Replace(input, @"\^7$", "");
|
||||
string RemoveTrailingColorCode(string input) => Regex.Replace(input, @"\^7$", "");
|
||||
|
||||
value = removeTrailingColorCode(value);
|
||||
defaultValue = removeTrailingColorCode(defaultValue);
|
||||
latchedValue = removeTrailingColorCode(latchedValue);
|
||||
value = RemoveTrailingColorCode(value);
|
||||
defaultValue = RemoveTrailingColorCode(defaultValue);
|
||||
latchedValue = RemoveTrailingColorCode(latchedValue);
|
||||
|
||||
return new Dvar<T>()
|
||||
return new Dvar<T>
|
||||
{
|
||||
Name = dvarName,
|
||||
Value = string.IsNullOrEmpty(value) ? default : (T)Convert.ChangeType(value, typeof(T)),
|
||||
@ -139,10 +140,12 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
};
|
||||
}
|
||||
|
||||
public virtual async Task<IStatusResponse> GetStatusAsync(IRConConnection connection)
|
||||
public virtual async Task<IStatusResponse> GetStatusAsync(IRConConnection connection, CancellationToken token = default)
|
||||
{
|
||||
var response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND_STATUS);
|
||||
_logger.LogDebug("Status Response {response}", string.Join(Environment.NewLine, response));
|
||||
var response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND_STATUS, "status", token);
|
||||
|
||||
_logger.LogDebug("Status Response {Response}", string.Join(Environment.NewLine, response));
|
||||
|
||||
return new StatusResponse
|
||||
{
|
||||
Clients = ClientsFromStatus(response).ToArray(),
|
||||
@ -183,13 +186,13 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
return (T)Convert.ChangeType(value, typeof(T));
|
||||
}
|
||||
|
||||
public async Task<bool> SetDvarAsync(IRConConnection connection, string dvarName, object dvarValue)
|
||||
public async Task<bool> SetDvarAsync(IRConConnection connection, string dvarName, object dvarValue, CancellationToken token = default)
|
||||
{
|
||||
string dvarString = (dvarValue is string str)
|
||||
var dvarString = (dvarValue is string str)
|
||||
? $"{dvarName} \"{str}\""
|
||||
: $"{dvarName} {dvarValue}";
|
||||
|
||||
return (await connection.SendQueryAsync(StaticHelpers.QueryType.SET_DVAR, dvarString)).Length > 0;
|
||||
return (await connection.SendQueryAsync(StaticHelpers.QueryType.SET_DVAR, dvarString, token)).Length > 0;
|
||||
}
|
||||
|
||||
private List<EFClient> ClientsFromStatus(string[] Status)
|
||||
|
@ -66,9 +66,14 @@ OnPlayerConnect()
|
||||
|
||||
player thread OnPlayerSpawned();
|
||||
player thread PlayerTrackingOnInterval();
|
||||
|
||||
// only toggle if it's enabled
|
||||
if ( IsDefined( level.nightModeEnabled ) && level.nightModeEnabled )
|
||||
{
|
||||
player ToggleNightMode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OnPlayerSpawned()
|
||||
{
|
||||
@ -496,7 +501,7 @@ OnExecuteCommand( event )
|
||||
}
|
||||
else
|
||||
{
|
||||
response = self GotoImpl( event.data );
|
||||
response = self GotoImpl( data );
|
||||
}
|
||||
break;
|
||||
case "Kill":
|
||||
@ -505,6 +510,9 @@ OnExecuteCommand( event )
|
||||
case "NightMode":
|
||||
NightModeImpl();
|
||||
break;
|
||||
case "SetSpectator":
|
||||
response = event.target SetSpectatorImpl();
|
||||
break;
|
||||
}
|
||||
|
||||
// send back the response to the origin, but only if they're not the target
|
||||
@ -707,3 +715,16 @@ ToggleNightMode()
|
||||
self SetClientDvar( "fx_draw", fxDraw );
|
||||
self SetClientDvar( "sv_cheats", 0 );
|
||||
}
|
||||
|
||||
SetSpectatorImpl()
|
||||
{
|
||||
if ( self.pers["team"] == "spectator" )
|
||||
{
|
||||
return self.name + " is already spectating";
|
||||
}
|
||||
|
||||
self [[level.spectator]]();
|
||||
self IPrintLnBold( "You have been moved to spectator" );
|
||||
|
||||
return self.name + " has been moved to spectator";
|
||||
}
|
||||
|
@ -23,12 +23,12 @@ namespace Integrations.Cod
|
||||
/// </summary>
|
||||
public class CodRConConnection : IRConConnection
|
||||
{
|
||||
static readonly ConcurrentDictionary<EndPoint, ConnectionState> ActiveQueries = new ConcurrentDictionary<EndPoint, ConnectionState>();
|
||||
private static readonly ConcurrentDictionary<EndPoint, ConnectionState> ActiveQueries = new();
|
||||
public IPEndPoint Endpoint { get; }
|
||||
public string RConPassword { get; }
|
||||
|
||||
private IRConParser parser;
|
||||
private IRConParserConfiguration config;
|
||||
private IRConParser _parser;
|
||||
private IRConParserConfiguration _config;
|
||||
private readonly ILogger _log;
|
||||
private readonly Encoding _gameEncoding;
|
||||
private readonly int _retryAttempts;
|
||||
@ -44,73 +44,105 @@ namespace Integrations.Cod
|
||||
|
||||
public void SetConfiguration(IRConParser parser)
|
||||
{
|
||||
this.parser = parser;
|
||||
config = parser.Configuration;
|
||||
this._parser = parser;
|
||||
_config = parser.Configuration;
|
||||
}
|
||||
|
||||
public async Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "")
|
||||
public async Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "",
|
||||
CancellationToken token = default)
|
||||
{
|
||||
if (!ActiveQueries.ContainsKey(this.Endpoint))
|
||||
{
|
||||
ActiveQueries.TryAdd(this.Endpoint, new ConnectionState());
|
||||
return await SendQueryAsyncInternal(type, parameters, token);
|
||||
}
|
||||
|
||||
var connectionState = ActiveQueries[this.Endpoint];
|
||||
private async Task<string[]> SendQueryAsyncInternal(StaticHelpers.QueryType type, string parameters = "", CancellationToken token = default)
|
||||
{
|
||||
if (!ActiveQueries.ContainsKey(Endpoint))
|
||||
{
|
||||
ActiveQueries.TryAdd(Endpoint, new ConnectionState());
|
||||
}
|
||||
|
||||
_log.LogDebug("Waiting for semaphore to be released [{endpoint}]", Endpoint);
|
||||
var connectionState = ActiveQueries[Endpoint];
|
||||
|
||||
_log.LogDebug("Waiting for semaphore to be released [{Endpoint}]", Endpoint);
|
||||
|
||||
// enter the semaphore so only one query is sent at a time per server.
|
||||
await connectionState.OnComplete.WaitAsync();
|
||||
try
|
||||
{
|
||||
await connectionState.OnComplete.WaitAsync(token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new RConException("Timed out waiting for access to rcon socket");
|
||||
}
|
||||
|
||||
var timeSinceLastQuery = (DateTime.Now - connectionState.LastQuery).TotalMilliseconds;
|
||||
|
||||
if (timeSinceLastQuery < config.FloodProtectInterval)
|
||||
if (timeSinceLastQuery < _config.FloodProtectInterval)
|
||||
{
|
||||
await Task.Delay(config.FloodProtectInterval - (int)timeSinceLastQuery);
|
||||
try
|
||||
{
|
||||
await Task.Delay(_config.FloodProtectInterval - (int)timeSinceLastQuery, token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new RConException("Timed out waiting for flood protect to expire");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (connectionState.OnComplete.CurrentCount == 0)
|
||||
{
|
||||
connectionState.OnComplete.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
connectionState.LastQuery = DateTime.Now;
|
||||
|
||||
_log.LogDebug("Semaphore has been released [{endpoint}]", Endpoint);
|
||||
_log.LogDebug("Query {@queryInfo}", new { endpoint=Endpoint.ToString(), type, parameters });
|
||||
_log.LogDebug("Semaphore has been released [{Endpoint}]", Endpoint);
|
||||
_log.LogDebug("Query {@QueryInfo}", new { endpoint=Endpoint.ToString(), type, parameters });
|
||||
|
||||
byte[] payload = null;
|
||||
bool waitForResponse = config.WaitForResponse;
|
||||
var waitForResponse = _config.WaitForResponse;
|
||||
|
||||
string convertEncoding(string text)
|
||||
string ConvertEncoding(string text)
|
||||
{
|
||||
byte[] convertedBytes = Utilities.EncodingType.GetBytes(text);
|
||||
var convertedBytes = Utilities.EncodingType.GetBytes(text);
|
||||
return _gameEncoding.GetString(convertedBytes);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
string convertedRConPassword = convertEncoding(RConPassword);
|
||||
string convertedParameters = convertEncoding(parameters);
|
||||
var convertedRConPassword = ConvertEncoding(RConPassword);
|
||||
var convertedParameters = ConvertEncoding(parameters);
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case StaticHelpers.QueryType.GET_DVAR:
|
||||
waitForResponse |= true;
|
||||
payload = string.Format(config.CommandPrefixes.RConGetDvar, convertedRConPassword, convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
||||
payload = string
|
||||
.Format(_config.CommandPrefixes.RConGetDvar, convertedRConPassword,
|
||||
convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
||||
break;
|
||||
case StaticHelpers.QueryType.SET_DVAR:
|
||||
payload = string.Format(config.CommandPrefixes.RConSetDvar, convertedRConPassword, convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
||||
payload = string
|
||||
.Format(_config.CommandPrefixes.RConSetDvar, convertedRConPassword,
|
||||
convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
||||
break;
|
||||
case StaticHelpers.QueryType.COMMAND:
|
||||
payload = string.Format(config.CommandPrefixes.RConCommand, convertedRConPassword, convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
||||
payload = string
|
||||
.Format(_config.CommandPrefixes.RConCommand, convertedRConPassword,
|
||||
convertedParameters + '\0').Select(Convert.ToByte).ToArray();
|
||||
break;
|
||||
case StaticHelpers.QueryType.GET_STATUS:
|
||||
waitForResponse |= true;
|
||||
payload = (config.CommandPrefixes.RConGetStatus + '\0').Select(Convert.ToByte).ToArray();
|
||||
payload = (_config.CommandPrefixes.RConGetStatus + '\0').Select(Convert.ToByte).ToArray();
|
||||
break;
|
||||
case StaticHelpers.QueryType.GET_INFO:
|
||||
waitForResponse |= true;
|
||||
payload = (config.CommandPrefixes.RConGetInfo + '\0').Select(Convert.ToByte).ToArray();
|
||||
payload = (_config.CommandPrefixes.RConGetInfo + '\0').Select(Convert.ToByte).ToArray();
|
||||
break;
|
||||
case StaticHelpers.QueryType.COMMAND_STATUS:
|
||||
waitForResponse |= true;
|
||||
payload = string.Format(config.CommandPrefixes.RConCommand, convertedRConPassword, "status\0").Select(Convert.ToByte).ToArray();
|
||||
payload = string.Format(_config.CommandPrefixes.RConCommand, convertedRConPassword, "status\0")
|
||||
.Select(Convert.ToByte).ToArray();
|
||||
break;
|
||||
}
|
||||
}
|
||||
@ -119,16 +151,24 @@ namespace Integrations.Cod
|
||||
// e.g: emoji -> windows-1252
|
||||
catch (OverflowException ex)
|
||||
{
|
||||
connectionState.OnComplete.Release(1);
|
||||
|
||||
using (LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||
{
|
||||
_log.LogError(ex, "Could not convert RCon data payload to desired encoding {encoding} {params}",
|
||||
_log.LogError(ex, "Could not convert RCon data payload to desired encoding {Encoding} {Params}",
|
||||
_gameEncoding.EncodingName, parameters);
|
||||
}
|
||||
|
||||
throw new RConException($"Invalid character encountered when converting encodings");
|
||||
}
|
||||
|
||||
finally
|
||||
{
|
||||
if (connectionState.OnComplete.CurrentCount == 0)
|
||||
{
|
||||
connectionState.OnComplete.Release();
|
||||
}
|
||||
}
|
||||
|
||||
byte[][] response = null;
|
||||
|
||||
retrySend:
|
||||
@ -137,7 +177,7 @@ namespace Integrations.Cod
|
||||
using (LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||
{
|
||||
_log.LogInformation(
|
||||
"Retrying RCon message ({connectionAttempts}/{allowedConnectionFailures} attempts) with parameters {payload}",
|
||||
"Retrying RCon message ({ConnectionAttempts}/{AllowedConnectionFailures} attempts) with parameters {Payload}",
|
||||
connectionState.ConnectionAttempts,
|
||||
_retryAttempts, parameters);
|
||||
}
|
||||
@ -149,22 +189,61 @@ namespace Integrations.Cod
|
||||
ExclusiveAddressUse = true,
|
||||
})
|
||||
{
|
||||
// wait for send to complete
|
||||
try
|
||||
{
|
||||
await connectionState.OnSentData.WaitAsync(token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new RConException("Timed out waiting for access to RCon send socket");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (connectionState.OnComplete.CurrentCount == 0 )
|
||||
{
|
||||
connectionState.OnComplete.Release();
|
||||
}
|
||||
}
|
||||
|
||||
// wait for receive to complete
|
||||
try
|
||||
{
|
||||
await connectionState.OnReceivedData.WaitAsync(token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new RConException("Timed out waiting for access to RCon receive socket");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (connectionState.OnComplete.CurrentCount == 0 )
|
||||
{
|
||||
connectionState.OnComplete.Release();
|
||||
}
|
||||
|
||||
if (connectionState.OnSentData.CurrentCount == 0)
|
||||
{
|
||||
connectionState.OnSentData.Release();
|
||||
}
|
||||
}
|
||||
|
||||
connectionState.SendEventArgs.UserToken = socket;
|
||||
connectionState.ConnectionAttempts++;
|
||||
await connectionState.OnSentData.WaitAsync();
|
||||
await connectionState.OnReceivedData.WaitAsync();
|
||||
connectionState.BytesReadPerSegment.Clear();
|
||||
bool exceptionCaught = false;
|
||||
|
||||
_log.LogDebug("Sending {payloadLength} bytes to [{endpoint}] ({connectionAttempts}/{allowedConnectionFailures})",
|
||||
connectionState.BytesReadPerSegment.Clear();
|
||||
var exceptionCaught = false;
|
||||
|
||||
_log.LogDebug("Sending {PayloadLength} bytes to [{Endpoint}] ({ConnectionAttempts}/{AllowedConnectionFailures})",
|
||||
payload.Length, Endpoint, connectionState.ConnectionAttempts, _retryAttempts);
|
||||
|
||||
try
|
||||
{
|
||||
connectionState.LastQuery = DateTime.Now;
|
||||
response = await SendPayloadAsync(payload, waitForResponse,
|
||||
_parser.OverrideTimeoutForCommand(parameters), token);
|
||||
|
||||
response = await SendPayloadAsync(payload, waitForResponse, parser.OverrideTimeoutForCommand(parameters));
|
||||
|
||||
if ((response.Length == 0 || response[0].Length == 0) && waitForResponse)
|
||||
if ((response?.Length == 0 || response[0].Length == 0) && waitForResponse)
|
||||
{
|
||||
throw new RConException("Expected response but got 0 bytes back");
|
||||
}
|
||||
@ -172,32 +251,48 @@ namespace Integrations.Cod
|
||||
connectionState.ConnectionAttempts = 0;
|
||||
}
|
||||
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// if we timed out due to the cancellation token,
|
||||
// we don't want to count that as an attempt
|
||||
connectionState.ConnectionAttempts = 0;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// we want to retry with a delay
|
||||
if (connectionState.ConnectionAttempts < _retryAttempts)
|
||||
{
|
||||
exceptionCaught = true;
|
||||
await Task.Delay(StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts));
|
||||
try
|
||||
{
|
||||
await Task.Delay(
|
||||
token != CancellationToken.None
|
||||
? StaticHelpers.SocketTimeout(100) // if using cancellation token we don't care about attempt count
|
||||
: StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts), token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw new RConException("Timed out waiting on delay retry");
|
||||
}
|
||||
|
||||
goto retrySend;
|
||||
}
|
||||
|
||||
using (LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||
{
|
||||
_log.LogWarning(
|
||||
"Made {connectionAttempts} attempts to send RCon data to server, but received no response",
|
||||
"Made {ConnectionAttempts} attempts to send RCon data to server, but received no response",
|
||||
connectionState.ConnectionAttempts);
|
||||
}
|
||||
connectionState.ConnectionAttempts = 0;
|
||||
throw new NetworkException("Reached maximum retry attempts to send RCon data to server");
|
||||
}
|
||||
|
||||
finally
|
||||
{
|
||||
// we don't want to release if we're going to retry the query
|
||||
if (connectionState.OnComplete.CurrentCount == 0 && !exceptionCaught)
|
||||
{
|
||||
connectionState.OnComplete.Release(1);
|
||||
connectionState.OnComplete.Release();
|
||||
}
|
||||
|
||||
if (connectionState.OnSentData.CurrentCount == 0)
|
||||
@ -214,14 +309,15 @@ namespace Integrations.Cod
|
||||
|
||||
if (response.Length == 0)
|
||||
{
|
||||
_log.LogDebug("Received empty response for RCon request {@query}", new { endpoint=Endpoint.ToString(), type, parameters });
|
||||
return new string[0];
|
||||
_log.LogDebug("Received empty response for RCon request {@Query}",
|
||||
new { endpoint = Endpoint.ToString(), type, parameters });
|
||||
return Array.Empty<string>();
|
||||
}
|
||||
|
||||
string responseString = type == StaticHelpers.QueryType.COMMAND_STATUS ?
|
||||
var responseString = type == StaticHelpers.QueryType.COMMAND_STATUS ?
|
||||
ReassembleSegmentedStatus(response) : RecombineMessages(response);
|
||||
|
||||
// note: not all games respond if the pasword is wrong or not set
|
||||
// note: not all games respond if the password is wrong or not set
|
||||
if (responseString.Contains("Invalid password") || responseString.Contains("rconpassword"))
|
||||
{
|
||||
throw new RConException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_RCON_INVALID"]);
|
||||
@ -232,26 +328,26 @@ namespace Integrations.Cod
|
||||
throw new RConException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_RCON_NOTSET"]);
|
||||
}
|
||||
|
||||
if (responseString.Contains(config.ServerNotRunningResponse))
|
||||
if (responseString.Contains(_config.ServerNotRunningResponse))
|
||||
{
|
||||
throw new ServerException(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_NOT_RUNNING"].FormatExt(Endpoint.ToString()));
|
||||
}
|
||||
|
||||
string responseHeaderMatch = Regex.Match(responseString, config.CommandPrefixes.RConResponse).Value;
|
||||
string[] headerSplit = responseString.Split(type == StaticHelpers.QueryType.GET_INFO ? config.CommandPrefixes.RconGetInfoResponseHeader : responseHeaderMatch);
|
||||
var responseHeaderMatch = Regex.Match(responseString, _config.CommandPrefixes.RConResponse).Value;
|
||||
var headerSplit = responseString.Split(type == StaticHelpers.QueryType.GET_INFO ? _config.CommandPrefixes.RconGetInfoResponseHeader : responseHeaderMatch);
|
||||
|
||||
if (headerSplit.Length != 2)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||
{
|
||||
_log.LogWarning("Invalid response header from server. Expected {expected}, but got {response}",
|
||||
config.CommandPrefixes.RConResponse, headerSplit.FirstOrDefault());
|
||||
_log.LogWarning("Invalid response header from server. Expected {Expected}, but got {Response}",
|
||||
_config.CommandPrefixes.RConResponse, headerSplit.FirstOrDefault());
|
||||
}
|
||||
|
||||
throw new RConException("Unexpected response header from server");
|
||||
}
|
||||
|
||||
string[] splitResponse = headerSplit.Last().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
var splitResponse = headerSplit.Last().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
return splitResponse;
|
||||
}
|
||||
|
||||
@ -261,14 +357,14 @@ namespace Integrations.Cod
|
||||
/// </summary>
|
||||
/// <param name="segments">array of segmented byte arrays</param>
|
||||
/// <returns></returns>
|
||||
public string ReassembleSegmentedStatus(byte[][] segments)
|
||||
private string ReassembleSegmentedStatus(byte[][] segments)
|
||||
{
|
||||
var splitStatusStrings = new List<string>();
|
||||
|
||||
foreach (byte[] segment in segments)
|
||||
foreach (var segment in segments)
|
||||
{
|
||||
string responseString = _gameEncoding.GetString(segment, 0, segment.Length);
|
||||
var statusHeaderMatch = config.StatusHeader.PatternMatcher.Match(responseString);
|
||||
var responseString = _gameEncoding.GetString(segment, 0, segment.Length);
|
||||
var statusHeaderMatch = _config.StatusHeader.PatternMatcher.Match(responseString);
|
||||
if (statusHeaderMatch.Success)
|
||||
{
|
||||
splitStatusStrings.Insert(0, responseString.TrimEnd('\0'));
|
||||
@ -276,7 +372,7 @@ namespace Integrations.Cod
|
||||
|
||||
else
|
||||
{
|
||||
splitStatusStrings.Add(responseString.Replace(config.CommandPrefixes.RConResponse, "").TrimEnd('\0'));
|
||||
splitStatusStrings.Add(responseString.Replace(_config.CommandPrefixes.RConResponse, "").TrimEnd('\0'));
|
||||
}
|
||||
}
|
||||
|
||||
@ -288,9 +384,9 @@ namespace Integrations.Cod
|
||||
/// </summary>
|
||||
/// <param name="payload"></param>
|
||||
/// <returns></returns>
|
||||
private string RecombineMessages(byte[][] payload)
|
||||
private string RecombineMessages(IReadOnlyList<byte[]> payload)
|
||||
{
|
||||
if (payload.Length == 1)
|
||||
if (payload.Count == 1)
|
||||
{
|
||||
return _gameEncoding.GetString(payload[0]).TrimEnd('\n') + '\n';
|
||||
}
|
||||
@ -298,12 +394,12 @@ namespace Integrations.Cod
|
||||
else
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
for (int i = 0; i < payload.Length; i++)
|
||||
for (int i = 0; i < payload.Count; i++)
|
||||
{
|
||||
string message = _gameEncoding.GetString(payload[i]).TrimEnd('\n') + '\n';
|
||||
if (i > 0)
|
||||
{
|
||||
message = message.Replace(config.CommandPrefixes.RConResponse, "");
|
||||
message = message.Replace(_config.CommandPrefixes.RConResponse, "");
|
||||
}
|
||||
builder.Append(message);
|
||||
}
|
||||
@ -312,11 +408,17 @@ namespace Integrations.Cod
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<byte[][]> SendPayloadAsync(byte[] payload, bool waitForResponse, TimeSpan overrideTimeout)
|
||||
private async Task<byte[][]> SendPayloadAsync(byte[] payload, bool waitForResponse, TimeSpan overrideTimeout,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var connectionState = ActiveQueries[this.Endpoint];
|
||||
var connectionState = ActiveQueries[Endpoint];
|
||||
var rconSocket = (Socket)connectionState.SendEventArgs.UserToken;
|
||||
|
||||
if (rconSocket is null)
|
||||
{
|
||||
throw new InvalidOperationException("State is not valid for socket operation");
|
||||
}
|
||||
|
||||
if (connectionState.ReceiveEventArgs.RemoteEndPoint == null &&
|
||||
connectionState.SendEventArgs.RemoteEndPoint == null)
|
||||
{
|
||||
@ -332,21 +434,37 @@ namespace Integrations.Cod
|
||||
connectionState.SendEventArgs.SetBuffer(payload);
|
||||
|
||||
// send the data to the server
|
||||
bool sendDataPending = rconSocket.SendToAsync(connectionState.SendEventArgs);
|
||||
var sendDataPending = rconSocket.SendToAsync(connectionState.SendEventArgs);
|
||||
|
||||
if (sendDataPending)
|
||||
{
|
||||
// the send has not been completed asynchronously
|
||||
// this really shouldn't ever happen because it's UDP
|
||||
var complete = false;
|
||||
try
|
||||
{
|
||||
complete = await connectionState.OnSentData.WaitAsync(StaticHelpers.SocketTimeout(1), token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
if(!await connectionState.OnSentData.WaitAsync(StaticHelpers.SocketTimeout(1)))
|
||||
if(!complete)
|
||||
{
|
||||
using(LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||
{
|
||||
_log.LogWarning("Socket timed out while sending RCon data on attempt {attempt}",
|
||||
_log.LogWarning("Socket timed out while sending RCon data on attempt {Attempt}",
|
||||
connectionState.ConnectionAttempts);
|
||||
}
|
||||
|
||||
rconSocket.Close();
|
||||
|
||||
if (connectionState.OnSentData.CurrentCount == 0)
|
||||
{
|
||||
connectionState.OnSentData.Release();
|
||||
}
|
||||
|
||||
throw new NetworkException("Timed out sending RCon data", rconSocket);
|
||||
}
|
||||
}
|
||||
@ -359,45 +477,61 @@ namespace Integrations.Cod
|
||||
connectionState.ReceiveEventArgs.SetBuffer(connectionState.ReceiveBuffer);
|
||||
|
||||
// get our response back
|
||||
bool receiveDataPending = rconSocket.ReceiveFromAsync(connectionState.ReceiveEventArgs);
|
||||
var receiveDataPending = rconSocket.ReceiveFromAsync(connectionState.ReceiveEventArgs);
|
||||
|
||||
if (receiveDataPending)
|
||||
{
|
||||
_log.LogDebug("Waiting to asynchronously receive data on attempt #{connectionAttempts}", connectionState.ConnectionAttempts);
|
||||
if (!await connectionState.OnReceivedData.WaitAsync(
|
||||
_log.LogDebug("Waiting to asynchronously receive data on attempt #{ConnectionAttempts}", connectionState.ConnectionAttempts);
|
||||
|
||||
var completed = false;
|
||||
|
||||
try
|
||||
{
|
||||
completed = await connectionState.OnReceivedData.WaitAsync(
|
||||
new[]
|
||||
{
|
||||
StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts),
|
||||
overrideTimeout
|
||||
}.Max()))
|
||||
}.Max(), token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
// ignored
|
||||
}
|
||||
|
||||
if (!completed)
|
||||
{
|
||||
if (connectionState.ConnectionAttempts > 1) // this reduces some spam for unstable connections
|
||||
{
|
||||
using (LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||
{
|
||||
_log.LogWarning(
|
||||
"Socket timed out while waiting for RCon response on attempt {attempt} with timeout delay of {timeout}",
|
||||
"Socket timed out while waiting for RCon response on attempt {Attempt} with timeout delay of {Timeout}",
|
||||
connectionState.ConnectionAttempts,
|
||||
StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts));
|
||||
}
|
||||
}
|
||||
|
||||
if (connectionState.OnReceivedData.CurrentCount == 0)
|
||||
{
|
||||
connectionState.OnReceivedData.Release();
|
||||
}
|
||||
|
||||
rconSocket.Close();
|
||||
throw new NetworkException("Timed out receiving RCon response", rconSocket);
|
||||
}
|
||||
}
|
||||
|
||||
rconSocket.Close();
|
||||
|
||||
return GetResponseData(connectionState);
|
||||
}
|
||||
|
||||
private byte[][] GetResponseData(ConnectionState connectionState)
|
||||
{
|
||||
var responseList = new List<byte[]>();
|
||||
int totalBytesRead = 0;
|
||||
var totalBytesRead = 0;
|
||||
|
||||
foreach (int bytesRead in connectionState.BytesReadPerSegment)
|
||||
foreach (var bytesRead in connectionState.BytesReadPerSegment)
|
||||
{
|
||||
responseList.Add(connectionState.ReceiveBuffer
|
||||
.Skip(totalBytesRead)
|
||||
@ -412,34 +546,52 @@ namespace Integrations.Cod
|
||||
|
||||
private void OnDataReceived(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
_log.LogDebug("Read {bytesTransferred} bytes from {endpoint}", e.BytesTransferred, e.RemoteEndPoint);
|
||||
_log.LogDebug("Read {BytesTransferred} bytes from {Endpoint}", e.BytesTransferred, e.RemoteEndPoint?.ToString());
|
||||
|
||||
// this occurs when we close the socket
|
||||
if (e.BytesTransferred == 0)
|
||||
{
|
||||
_log.LogDebug("No bytes were transmitted so the connection was probably closed");
|
||||
|
||||
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||
var semaphore = ActiveQueries[Endpoint].OnReceivedData;
|
||||
|
||||
try
|
||||
{
|
||||
if (semaphore.CurrentCount == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored because we can have the socket operation cancelled (which releases the semaphore) but
|
||||
// this thread is not notified because it's an event
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (sender is not Socket sock)
|
||||
{
|
||||
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||
var semaphore = ActiveQueries[Endpoint].OnReceivedData;
|
||||
|
||||
try
|
||||
{
|
||||
if (semaphore.CurrentCount == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored because we can have the socket operation cancelled (which releases the semaphore) but
|
||||
// this thread is not notified because it's an event
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
var state = ActiveQueries[this.Endpoint];
|
||||
var state = ActiveQueries[Endpoint];
|
||||
state.BytesReadPerSegment.Add(e.BytesTransferred);
|
||||
|
||||
// I don't even want to know why this works for getting more data from Cod4x
|
||||
@ -450,18 +602,18 @@ namespace Integrations.Cod
|
||||
try
|
||||
{
|
||||
var totalBytesTransferred = e.BytesTransferred;
|
||||
_log.LogDebug("{total} total bytes transferred with {available} bytes remaining", totalBytesTransferred,
|
||||
_log.LogDebug("{Total} total bytes transferred with {Available} bytes remaining", totalBytesTransferred,
|
||||
sock.Available);
|
||||
// we still have available data so the payload was segmented
|
||||
while (sock.Available > 0)
|
||||
{
|
||||
_log.LogDebug("{available} more bytes to be read", sock.Available);
|
||||
_log.LogDebug("{Available} more bytes to be read", sock.Available);
|
||||
|
||||
var bufferSpaceAvailable = sock.Available + totalBytesTransferred - state.ReceiveBuffer.Length;
|
||||
if (bufferSpaceAvailable >= 0)
|
||||
{
|
||||
_log.LogWarning(
|
||||
"Not enough buffer space to store incoming data {bytesNeeded} additional bytes required",
|
||||
"Not enough buffer space to store incoming data {BytesNeeded} additional bytes required",
|
||||
bufferSpaceAvailable);
|
||||
continue;
|
||||
}
|
||||
@ -474,8 +626,8 @@ namespace Integrations.Cod
|
||||
continue;
|
||||
}
|
||||
|
||||
_log.LogDebug("Read {bytesTransferred} synchronous bytes from {endpoint}",
|
||||
state.ReceiveEventArgs.BytesTransferred, e.RemoteEndPoint);
|
||||
_log.LogDebug("Read {BytesTransferred} synchronous bytes from {Endpoint}",
|
||||
state.ReceiveEventArgs.BytesTransferred, e.RemoteEndPoint?.ToString());
|
||||
// we need to increment this here because the callback isn't executed if there's no pending IO
|
||||
state.BytesReadPerSegment.Add(state.ReceiveEventArgs.BytesTransferred);
|
||||
totalBytesTransferred += state.ReceiveEventArgs.BytesTransferred;
|
||||
@ -489,23 +641,39 @@ namespace Integrations.Cod
|
||||
|
||||
finally
|
||||
{
|
||||
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||
var semaphore = ActiveQueries[Endpoint].OnReceivedData;
|
||||
try
|
||||
{
|
||||
if (semaphore.CurrentCount == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored because we can have the socket operation cancelled (which releases the semaphore) but
|
||||
// this thread is not notified because it's an event
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void OnDataSent(object sender, SocketAsyncEventArgs e)
|
||||
{
|
||||
_log.LogDebug("Sent {byteCount} bytes to {endpoint}", e.Buffer?.Length, e.ConnectSocket?.RemoteEndPoint);
|
||||
_log.LogDebug("Sent {ByteCount} bytes to {Endpoint}", e.Buffer?.Length, e.ConnectSocket?.RemoteEndPoint?.ToString());
|
||||
|
||||
var semaphore = ActiveQueries[this.Endpoint].OnSentData;
|
||||
var semaphore = ActiveQueries[Endpoint].OnSentData;
|
||||
try
|
||||
{
|
||||
if (semaphore.CurrentCount == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// ignored because we can have the socket operation cancelled (which releases the semaphore) but
|
||||
// this thread is not notified because it's an event
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -48,12 +48,12 @@ namespace Integrations.Source
|
||||
_activeQuery.Dispose();
|
||||
}
|
||||
|
||||
public async Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "")
|
||||
public async Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "", CancellationToken token = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _activeQuery.WaitAsync();
|
||||
await WaitForAvailable();
|
||||
await _activeQuery.WaitAsync(token);
|
||||
await WaitForAvailable(token);
|
||||
|
||||
if (_needNewSocket)
|
||||
{
|
||||
@ -66,7 +66,7 @@ namespace Integrations.Source
|
||||
// ignored
|
||||
}
|
||||
|
||||
await Task.Delay(ConnectionTimeout);
|
||||
await Task.Delay(ConnectionTimeout, token);
|
||||
_rconClient = _rconClientFactory.CreateClient(_ipEndPoint);
|
||||
_authenticated = false;
|
||||
_needNewSocket = false;
|
||||
@ -147,12 +147,12 @@ namespace Integrations.Source
|
||||
}
|
||||
}
|
||||
|
||||
private async Task WaitForAvailable()
|
||||
private async Task WaitForAvailable(CancellationToken token)
|
||||
{
|
||||
var diff = DateTime.Now - _lastQuery;
|
||||
if (diff < FloodDelay)
|
||||
{
|
||||
await Task.Delay(FloodDelay - diff);
|
||||
await Task.Delay(FloodDelay - diff, token);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -10,7 +10,7 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.22.1" PrivateAssets="All" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.28.1" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
|
@ -23,7 +23,7 @@
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.22.1" PrivateAssets="All" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.28.1" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
|
@ -19,7 +19,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.22.1" PrivateAssets="All" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.28.1" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
|
@ -16,7 +16,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.22.1" PrivateAssets="All" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.28.1" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
|
@ -271,6 +271,24 @@ let commands = [{
|
||||
}
|
||||
sendScriptCommand(gameEvent.Owner, 'NightMode', gameEvent.Origin, undefined, undefined);
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'setspectator',
|
||||
description: 'sets a player as spectator',
|
||||
alias: 'spec',
|
||||
permission: 'Administrator',
|
||||
targetRequired: true,
|
||||
arguments: [{
|
||||
name: 'player',
|
||||
required: true
|
||||
}],
|
||||
supportedGames: ['IW4'],
|
||||
execute: (gameEvent) => {
|
||||
if (!validateEnabled(gameEvent.Owner, gameEvent.Origin)) {
|
||||
return;
|
||||
}
|
||||
sendScriptCommand(gameEvent.Owner, 'SetSpectator', gameEvent.Origin, gameEvent.Target, undefined);
|
||||
}
|
||||
}];
|
||||
|
||||
const sendScriptCommand = (server, command, origin, target, data) => {
|
||||
@ -289,6 +307,11 @@ const sendEvent = (server, responseExpected, event, subtype, origin, target, dat
|
||||
const start = new Date();
|
||||
|
||||
while (pendingOut && pendingCheckCount <= 10) {
|
||||
if (server.Throttled) {
|
||||
logger.WriteWarning('Server is throttled, so we are not attempting to send data');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const out = server.GetServerDvar(outDvar);
|
||||
pendingOut = !(out == null || out === '' || out === 'null');
|
||||
@ -300,6 +323,7 @@ const sendEvent = (server, responseExpected, event, subtype, origin, target, dat
|
||||
logger.WriteDebug('Waiting for event bus to be cleared');
|
||||
System.Threading.Tasks.Task.Delay(1000).Wait();
|
||||
}
|
||||
|
||||
pendingCheckCount++;
|
||||
}
|
||||
|
||||
@ -379,6 +403,10 @@ const initialize = (server) => {
|
||||
};
|
||||
|
||||
const pollForEvents = server => {
|
||||
if (server.Throttled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const logger = _serviceResolver.ResolveService('ILogger');
|
||||
|
||||
let input;
|
||||
|
@ -17,7 +17,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.22.1" PrivateAssets="All" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.28.1" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
|
@ -20,7 +20,7 @@
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.22.1" PrivateAssets="All" />
|
||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.2.28.1" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
@ -1190,7 +1190,7 @@ namespace SharedLibraryCore.Commands
|
||||
|
||||
public static async Task<string> GetNextMap(Server s, ITranslationLookup lookup)
|
||||
{
|
||||
var mapRotation = (await s.GetDvarAsync<string>("sv_mapRotation")).Value?.ToLower() ?? "";
|
||||
var mapRotation = (await s.GetDvarAsync<string>("sv_mapRotation", token: s.Manager.CancellationToken)).Value?.ToLower() ?? "";
|
||||
var regexMatches = Regex.Matches(mapRotation,
|
||||
@"((?:gametype|exec) +(?:([a-z]{1,4})(?:.cfg)?))? *map ([a-z|_|\d]+)", RegexOptions.IgnoreCase)
|
||||
.ToList();
|
||||
|
@ -20,6 +20,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
|
||||
public enum MetaType
|
||||
{
|
||||
All = -1,
|
||||
Other,
|
||||
Information,
|
||||
AliasUpdate,
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using SharedLibraryCore.RCon;
|
||||
|
||||
namespace SharedLibraryCore.Interfaces
|
||||
@ -14,7 +15,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <param name="type">type of RCon query to perform</param>
|
||||
/// <param name="parameters">optional parameter list</param>
|
||||
/// <returns></returns>
|
||||
Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "");
|
||||
Task<string[]> SendQueryAsync(StaticHelpers.QueryType type, string parameters = "", CancellationToken token = default);
|
||||
|
||||
/// <summary>
|
||||
/// sets the rcon parser
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using static SharedLibraryCore.Server;
|
||||
|
||||
@ -52,7 +53,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <param name="dvarName">name of DVAR</param>
|
||||
/// <param name="fallbackValue">default value to return if dvar retrieval fails</param>
|
||||
/// <returns></returns>
|
||||
Task<Dvar<T>> GetDvarAsync<T>(IRConConnection connection, string dvarName, T fallbackValue = default);
|
||||
Task<Dvar<T>> GetDvarAsync<T>(IRConConnection connection, string dvarName, T fallbackValue = default, CancellationToken token = default);
|
||||
|
||||
/// <summary>
|
||||
/// set value of DVAR by name
|
||||
@ -61,7 +62,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <param name="dvarName">name of DVAR to set</param>
|
||||
/// <param name="dvarValue">value to set DVAR to</param>
|
||||
/// <returns></returns>
|
||||
Task<bool> SetDvarAsync(IRConConnection connection, string dvarName, object dvarValue);
|
||||
Task<bool> SetDvarAsync(IRConConnection connection, string dvarName, object dvarValue, CancellationToken token = default);
|
||||
|
||||
/// <summary>
|
||||
/// executes a console command on the server
|
||||
@ -69,7 +70,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <param name="connection">RCon connection to use</param>
|
||||
/// <param name="command">console command to execute</param>
|
||||
/// <returns></returns>
|
||||
Task<string[]> ExecuteCommandAsync(IRConConnection connection, string command);
|
||||
Task<string[]> ExecuteCommandAsync(IRConConnection connection, string command, CancellationToken token = default);
|
||||
|
||||
/// <summary>
|
||||
/// get the list of connected clients from status response
|
||||
@ -78,7 +79,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <returns>
|
||||
/// <see cref="IStatusResponse" />
|
||||
/// </returns>
|
||||
Task<IStatusResponse> GetStatusAsync(IRConConnection connection);
|
||||
Task<IStatusResponse> GetStatusAsync(IRConConnection connection, CancellationToken token = default);
|
||||
|
||||
/// <summary>
|
||||
/// retrieves the value of given dvar key if it exists in the override dict
|
||||
|
@ -377,7 +377,7 @@ namespace SharedLibraryCore
|
||||
{
|
||||
try
|
||||
{
|
||||
return (await this.GetDvarAsync("sv_customcallbacks", "0")).Value == "1";
|
||||
return (await this.GetDvarAsync("sv_customcallbacks", "0", Manager.CancellationToken)).Value == "1";
|
||||
}
|
||||
|
||||
catch (DvarException)
|
||||
@ -391,11 +391,11 @@ namespace SharedLibraryCore
|
||||
public string[] ExecuteServerCommand(string command)
|
||||
{
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
tokenSource.CancelAfter(TimeSpan.FromMilliseconds(400));
|
||||
tokenSource.CancelAfter(TimeSpan.FromSeconds(0.5));
|
||||
|
||||
try
|
||||
{
|
||||
return this.ExecuteCommandAsync(command).WithWaitCancellation(tokenSource.Token).GetAwaiter().GetResult();
|
||||
return this.ExecuteCommandAsync(command, tokenSource.Token).GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -406,11 +406,10 @@ namespace SharedLibraryCore
|
||||
public string GetServerDvar(string dvarName)
|
||||
{
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
tokenSource.CancelAfter(TimeSpan.FromMilliseconds(400));
|
||||
tokenSource.CancelAfter(TimeSpan.FromSeconds(0.5));
|
||||
try
|
||||
{
|
||||
return this.GetDvarAsync<string>(dvarName).WithWaitCancellation(tokenSource.Token).GetAwaiter()
|
||||
.GetResult()?.Value;
|
||||
return this.GetDvarAsync<string>(dvarName, token: tokenSource.Token).GetAwaiter().GetResult().Value;
|
||||
}
|
||||
catch
|
||||
{
|
||||
@ -421,12 +420,11 @@ namespace SharedLibraryCore
|
||||
public bool SetServerDvar(string dvarName, string dvarValue)
|
||||
{
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
tokenSource.CancelAfter(TimeSpan.FromMilliseconds(400));
|
||||
tokenSource.CancelAfter(TimeSpan.FromSeconds(0.5));
|
||||
try
|
||||
{
|
||||
this.SetDvarAsync(dvarName, dvarValue).WithWaitCancellation(tokenSource.Token).GetAwaiter().GetResult();
|
||||
this.SetDvarAsync(dvarName, dvarValue, tokenSource.Token).GetAwaiter().GetResult();
|
||||
return true;
|
||||
|
||||
}
|
||||
catch
|
||||
{
|
||||
|
@ -597,51 +597,16 @@ namespace SharedLibraryCore.Services
|
||||
/// <returns></returns>
|
||||
public virtual async Task UpdateLevel(Permission newPermission, EFClient temporalClient, EFClient origin)
|
||||
{
|
||||
await using var ctx = _contextFactory.CreateContext();
|
||||
var entity = await ctx.Clients
|
||||
.Where(_client => _client.ClientId == temporalClient.ClientId)
|
||||
await using var context = _contextFactory.CreateContext();
|
||||
var entity = await context.Clients
|
||||
.Where(client => client.ClientId == temporalClient.ClientId)
|
||||
.FirstAsync();
|
||||
|
||||
var oldPermission = entity.Level;
|
||||
_logger.LogInformation("Updating {ClientId} from {OldPermission} to {NewPermission} ",
|
||||
temporalClient.ClientId, entity.Level, newPermission);
|
||||
|
||||
entity.Level = newPermission;
|
||||
await ctx.SaveChangesAsync();
|
||||
|
||||
using (LogContext.PushProperty("Server", temporalClient?.CurrentServer?.ToString()))
|
||||
{
|
||||
_logger.LogInformation("Updated {clientId} to {newPermission}", temporalClient.ClientId, newPermission);
|
||||
|
||||
var linkedPermissionSet = new[] { Permission.Banned, Permission.Flagged };
|
||||
// if their permission level has been changed to level that needs to be updated on all accounts
|
||||
if (linkedPermissionSet.Contains(newPermission) || linkedPermissionSet.Contains(oldPermission))
|
||||
{
|
||||
//get all clients that have the same linkId
|
||||
var iqMatchingClients = ctx.Clients
|
||||
.Where(_client => _client.AliasLinkId == entity.AliasLinkId);
|
||||
|
||||
var iqLinkClients = new List<Data.Models.Client.EFClient>().AsQueryable();
|
||||
if (!_appConfig.EnableImplicitAccountLinking)
|
||||
{
|
||||
var linkIds = await ctx.Aliases.Where(alias =>
|
||||
alias.IPAddress != null && alias.IPAddress == temporalClient.IPAddress)
|
||||
.Select(alias => alias.LinkId)
|
||||
.ToListAsync();
|
||||
iqLinkClients = ctx.Clients.Where(client => linkIds.Contains(client.AliasLinkId));
|
||||
}
|
||||
|
||||
// this updates the level for all the clients with the same LinkId
|
||||
// only if their new level is flagged or banned
|
||||
await iqMatchingClients.Union(iqLinkClients).ForEachAsync(_client =>
|
||||
{
|
||||
_client.Level = newPermission;
|
||||
_logger.LogInformation("Updated linked {clientId} to {newPermission}", _client.ClientId,
|
||||
newPermission);
|
||||
});
|
||||
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
await context.SaveChangesAsync();
|
||||
temporalClient.Level = newPermission;
|
||||
}
|
||||
|
||||
|
@ -116,7 +116,7 @@ namespace SharedLibraryCore.Services
|
||||
}
|
||||
|
||||
private static readonly EFPenalty.PenaltyType[] LinkedPenalties =
|
||||
{ EFPenalty.PenaltyType.Ban, EFPenalty.PenaltyType.Flag };
|
||||
{ EFPenalty.PenaltyType.Ban, EFPenalty.PenaltyType.Flag, EFPenalty.PenaltyType.TempBan };
|
||||
|
||||
private static readonly Expression<Func<EFPenalty, bool>> Filter = p =>
|
||||
LinkedPenalties.Contains(p.Type) && p.Active && (p.Expires == null || p.Expires > DateTime.UtcNow);
|
||||
|
@ -4,7 +4,7 @@
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<PackageId>RaidMax.IW4MAdmin.SharedLibraryCore</PackageId>
|
||||
<Version>2022.2.22.1</Version>
|
||||
<Version>2022.2.28.1</Version>
|
||||
<Authors>RaidMax</Authors>
|
||||
<Company>Forever None</Company>
|
||||
<Configurations>Debug;Release;Prerelease</Configurations>
|
||||
@ -19,7 +19,7 @@
|
||||
<IsPackable>true</IsPackable>
|
||||
<PackageLicenseExpression>MIT</PackageLicenseExpression>
|
||||
<Description>Shared Library for IW4MAdmin</Description>
|
||||
<PackageVersion>2022.2.22.1</PackageVersion>
|
||||
<PackageVersion>2022.2.28.1</PackageVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Prerelease|AnyCPU'">
|
||||
|
@ -723,14 +723,21 @@ namespace SharedLibraryCore
|
||||
.Replace('/', '_');
|
||||
}
|
||||
|
||||
public static Task<Dvar<T>> GetDvarAsync<T>(this Server server, string dvarName, T fallbackValue = default)
|
||||
public static async Task<Dvar<T>> GetDvarAsync<T>(this Server server, string dvarName,
|
||||
T fallbackValue = default, CancellationToken token = default)
|
||||
{
|
||||
return server.RconParser.GetDvarAsync(server.RemoteConnection, dvarName, fallbackValue);
|
||||
return await server.RconParser.GetDvarAsync(server.RemoteConnection, dvarName, fallbackValue, token);
|
||||
}
|
||||
|
||||
public static async Task<Dvar<T>> GetDvarAsync<T>(this Server server, string dvarName,
|
||||
T fallbackValue = default)
|
||||
{
|
||||
return await GetDvarAsync(server, dvarName, fallbackValue, default);
|
||||
}
|
||||
|
||||
public static async Task<Dvar<T>> GetMappedDvarValueOrDefaultAsync<T>(this Server server, string dvarName,
|
||||
string infoResponseName = null, IDictionary<string, string> infoResponse = null,
|
||||
T overrideDefault = default)
|
||||
T overrideDefault = default, CancellationToken token = default)
|
||||
{
|
||||
// todo: unit test this
|
||||
var mappedKey = server.RconParser.GetOverrideDvarName(dvarName);
|
||||
@ -749,22 +756,32 @@ namespace SharedLibraryCore
|
||||
};
|
||||
}
|
||||
|
||||
return await server.GetDvarAsync(mappedKey, defaultValue);
|
||||
return await server.GetDvarAsync(mappedKey, defaultValue, token: token);
|
||||
}
|
||||
|
||||
public static Task SetDvarAsync(this Server server, string dvarName, object dvarValue)
|
||||
public static async Task SetDvarAsync(this Server server, string dvarName, object dvarValue, CancellationToken token = default)
|
||||
{
|
||||
return server.RconParser.SetDvarAsync(server.RemoteConnection, dvarName, dvarValue);
|
||||
await server.RconParser.SetDvarAsync(server.RemoteConnection, dvarName, dvarValue, token);
|
||||
}
|
||||
|
||||
public static async Task SetDvarAsync(this Server server, string dvarName, object dvarValue)
|
||||
{
|
||||
await SetDvarAsync(server, dvarName, dvarValue, default);
|
||||
}
|
||||
|
||||
public static async Task<string[]> ExecuteCommandAsync(this Server server, string commandName, CancellationToken token = default)
|
||||
{
|
||||
return await server.RconParser.ExecuteCommandAsync(server.RemoteConnection, commandName, token);
|
||||
}
|
||||
|
||||
public static async Task<string[]> ExecuteCommandAsync(this Server server, string commandName)
|
||||
{
|
||||
return await server.RconParser.ExecuteCommandAsync(server.RemoteConnection, commandName);
|
||||
return await ExecuteCommandAsync(server, commandName, default);
|
||||
}
|
||||
|
||||
public static Task<IStatusResponse> GetStatusAsync(this Server server)
|
||||
public static Task<IStatusResponse> GetStatusAsync(this Server server, CancellationToken token)
|
||||
{
|
||||
return server.RconParser.GetStatusAsync(server.RemoteConnection);
|
||||
return server.RconParser.GetStatusAsync(server.RemoteConnection, token);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -53,6 +53,14 @@ namespace WebfrontCore.Controllers
|
||||
client.SetAdditionalProperty(EFMeta.ClientTag, tag.LinkedMeta.Value);
|
||||
}
|
||||
|
||||
// even though we haven't set their level to "banned" yet
|
||||
// (ie they haven't reconnected with the infringing player identifier)
|
||||
// we want to show them as banned as to not confuse people.
|
||||
if (activePenalties.Any(penalty => penalty.Type == EFPenalty.PenaltyType.Ban))
|
||||
{
|
||||
client.Level = Data.Models.Client.EFClient.Permission.Banned;
|
||||
}
|
||||
|
||||
var displayLevelInt = (int)client.Level;
|
||||
var displayLevel = client.Level.ToLocalizedLevelName();
|
||||
|
||||
|
@ -38,11 +38,12 @@ namespace WebfrontCore.ViewComponents
|
||||
return View("_List", meta);
|
||||
}
|
||||
|
||||
public static async Task<IEnumerable<IClientMeta>> GetClientMeta(IMetaService metaService, MetaType? metaType, EFClient.Permission level, ClientPaginationRequest request)
|
||||
public static async Task<IEnumerable<IClientMeta>> GetClientMeta(IMetaService metaService, MetaType? metaType,
|
||||
EFClient.Permission level, ClientPaginationRequest request)
|
||||
{
|
||||
IEnumerable<IClientMeta> meta = null;
|
||||
|
||||
if (metaType == null) // all types
|
||||
if (metaType is null or MetaType.All)
|
||||
{
|
||||
meta = await metaService.GetRuntimeMeta(request);
|
||||
}
|
||||
|
@ -146,23 +146,23 @@
|
||||
<partial name="Meta/_Information.cshtml" model="@Model.Meta"/>
|
||||
</div>
|
||||
|
||||
<div class="row border-bottom bg-dark">
|
||||
<div class="d-md-flex flex-fill align-items-center bg-dark">
|
||||
<div class="text-center bg-dark p-2 pl-3 pr-4 text-muted" id="filter_meta_container_button">
|
||||
<span class="oi oi-sort-ascending"></span>
|
||||
<div class="row border-bottom">
|
||||
<div class="d-md-flex flex-fill">
|
||||
<div class="bg-dark p-2 pl-3 pr-3 text-center text-muted border-0 align-self-stretch align-middle" id="filter_meta_container_button">
|
||||
<span class="text-primary" id="meta_filter_dropdown_icon">▼</span>
|
||||
<a>@ViewBag.Localization["WEBFRONT_CLIENT_META_FILTER"]</a>
|
||||
</div>
|
||||
<div id="filter_meta_container" class="d-none d-md-flex flex-md-fill flex-md-wrap">
|
||||
<a asp-action="ProfileAsync" asp-controller="Client"
|
||||
class="nav-link p-2 pl-3 pr-3 text-center col-12 col-md-auto text-md-left @(!Model.MetaFilterType.HasValue ? "btn-primary text-white" : "text-muted")"
|
||||
asp-route-id="@Model.ClientId">
|
||||
@ViewBag.Localization["META_TYPE_ALL_NAME"]
|
||||
</a>
|
||||
@{ var metaTypes = Enum.GetValues(typeof(MetaType))
|
||||
@{
|
||||
const int defaultTabCount = 5;
|
||||
var metaTypes = Enum.GetValues(typeof(MetaType))
|
||||
.Cast<MetaType>()
|
||||
.Where(type => !ignoredMetaTypes.Contains(type))
|
||||
.ToList(); }
|
||||
@foreach (var type in metaTypes.Take(4))
|
||||
.OrderByDescending(type => type == MetaType.All)
|
||||
.ToList();
|
||||
var selectedMeta = metaTypes.FirstOrDefault(meta => metaTypes.IndexOf(Model.MetaFilterType ?? MetaType.All) >= defaultTabCount && meta != MetaType.All && meta == Model.MetaFilterType);
|
||||
}
|
||||
@foreach (var type in metaTypes.Take(defaultTabCount - 1).Append(selectedMeta == MetaType.Other ? metaTypes[defaultTabCount - 1] : selectedMeta))
|
||||
{
|
||||
<a asp-action="ProfileAsync" asp-controller="Client"
|
||||
class="meta-filter nav-link p-2 pl-3 pr-3 text-center @(Model.MetaFilterType.HasValue && Model.MetaFilterType.Value.ToString() == type.ToString() ? "btn-primary text-white" : "text-muted")"
|
||||
@ -172,9 +172,8 @@
|
||||
@type.ToTranslatedName()
|
||||
</a>
|
||||
}
|
||||
<a href="#" class="nav-link p-2 pl-3 pr-3 text-center text-muted d-none d-md-block" id="expand-meta-filters">...</a>
|
||||
<div class="d-block d-md-none" id="additional-meta-filter">
|
||||
@foreach (var type in metaTypes.Skip(4))
|
||||
<div class="d-md-none" id="additional_meta_filter">
|
||||
@foreach (var type in (selectedMeta == MetaType.Other ? metaTypes.Skip(defaultTabCount) : metaTypes.Skip(defaultTabCount).Append(metaTypes[defaultTabCount - 1])).Where(meta => selectedMeta == MetaType.Other || meta != selectedMeta))
|
||||
{
|
||||
<a asp-action="ProfileAsync" asp-controller="Client"
|
||||
class="meta-filter nav-link p-2 pl-3 pr-3 text-center @(Model.MetaFilterType.HasValue && Model.MetaFilterType.Value.ToString() == type.ToString() ? "btn-primary text-white" : "text-muted")"
|
||||
|
@ -35,16 +35,10 @@
|
||||
startAt = $('.loader-data-time').last().data('time');
|
||||
|
||||
$('#filter_meta_container_button').click(function () {
|
||||
$('#filter_meta_container').hide().removeClass('d-none').addClass('d-block').slideDown();
|
||||
$('#additional-meta-filter').removeClass('d-md-none').addClass('d-flex').slideDown();
|
||||
$('#expand-meta-filters').removeClass('d-md-block');
|
||||
$('#filter_meta_container').removeClass('d-none').addClass('flex-md-column');
|
||||
$('#additional_meta_filter').removeClass('d-md-none');
|
||||
});
|
||||
|
||||
$('#expand-meta-filters').click(function () {
|
||||
$('#additional-meta-filter').removeClass('d-md-none').addClass('d-flex').slideDown();
|
||||
$('#expand-meta-filters').removeClass('d-md-block');
|
||||
})
|
||||
|
||||
/*
|
||||
* load context of chat
|
||||
*/
|
||||
|
@ -15,6 +15,8 @@ $(document).ready(() => {
|
||||
return 0;
|
||||
}
|
||||
|
||||
setInterval(refreshScoreboard, 5000);
|
||||
|
||||
$(window.location.hash).tab('show');
|
||||
$(`${window.location.hash}_nav`).addClass('active');
|
||||
|
||||
@ -32,5 +34,3 @@ function setupDataSorting() {
|
||||
refreshScoreboard();
|
||||
})
|
||||
}
|
||||
|
||||
setInterval(refreshScoreboard, 5000);
|
||||
|
Reference in New Issue
Block a user