Compare commits
6 Commits
2022.02.09
...
2022.02.14
Author | SHA1 | Date | |
---|---|---|---|
037fac5786 | |||
f4b892d8f4 | |||
3640d1df54 | |||
f3c6b10a35 | |||
4dec284b31 | |||
c9cf7be341 |
@ -236,13 +236,6 @@ namespace IW4MAdmin.Application
|
||||
.Select(ut => ut.Key)
|
||||
.ToList();
|
||||
|
||||
// this is to prevent the log reader from starting before the initial
|
||||
// query of players on the server
|
||||
if (serverTasksToRemove.Count > 0)
|
||||
{
|
||||
IsInitialized = true;
|
||||
}
|
||||
|
||||
// remove the update tasks as they have completed
|
||||
foreach (var serverId in serverTasksToRemove.Where(serverId => runningUpdateTasks.ContainsKey(serverId)))
|
||||
{
|
||||
@ -530,6 +523,7 @@ namespace IW4MAdmin.Application
|
||||
|
||||
Console.WriteLine(_translationLookup["MANAGER_COMMUNICATION_INFO"]);
|
||||
await InitializeServers();
|
||||
IsInitialized = true;
|
||||
}
|
||||
|
||||
private async Task InitializeServers()
|
||||
|
@ -18,14 +18,22 @@ namespace IW4MAdmin.Application.Factories
|
||||
public IGameLogReader CreateGameLogReader(Uri[] logUris, IEventParser eventParser)
|
||||
{
|
||||
var baseUri = logUris[0];
|
||||
if (baseUri.Scheme == Uri.UriSchemeHttp)
|
||||
if (baseUri.Scheme == Uri.UriSchemeHttp || baseUri.Scheme == Uri.UriSchemeHttps)
|
||||
{
|
||||
return new GameLogReaderHttp(logUris, eventParser, _serviceProvider.GetRequiredService<ILogger<GameLogReaderHttp>>());
|
||||
return new GameLogReaderHttp(logUris, eventParser,
|
||||
_serviceProvider.GetRequiredService<ILogger<GameLogReaderHttp>>());
|
||||
}
|
||||
|
||||
else if (baseUri.Scheme == Uri.UriSchemeFile)
|
||||
if (baseUri.Scheme == Uri.UriSchemeFile)
|
||||
{
|
||||
return new GameLogReader(baseUri.LocalPath, eventParser, _serviceProvider.GetRequiredService<ILogger<GameLogReader>>());
|
||||
return new GameLogReader(baseUri.LocalPath, eventParser,
|
||||
_serviceProvider.GetRequiredService<ILogger<GameLogReader>>());
|
||||
}
|
||||
|
||||
if (baseUri.Scheme == Uri.UriSchemeNetTcp)
|
||||
{
|
||||
return new NetworkGameLogReader(logUris, eventParser,
|
||||
_serviceProvider.GetRequiredService<ILogger<NetworkGameLogReader>>());
|
||||
}
|
||||
|
||||
throw new NotImplementedException($"No log reader implemented for Uri scheme \"{baseUri.Scheme}\"");
|
||||
|
@ -21,7 +21,7 @@ namespace IW4MAdmin.Application.IO
|
||||
{
|
||||
_reader = gameLogReaderFactory.CreateGameLogReader(gameLogUris, server.EventParser);
|
||||
_server = server;
|
||||
_ignoreBots = server?.Manager.GetApplicationSettings().Configuration().IgnoreBots ?? false;
|
||||
_ignoreBots = server.Manager.GetApplicationSettings().Configuration()?.IgnoreBots ?? false;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@ -69,7 +69,7 @@ namespace IW4MAdmin.Application.IO
|
||||
return;
|
||||
}
|
||||
|
||||
var events = await _reader.ReadEventsFromLog(fileDiff, previousFileSize);
|
||||
var events = await _reader.ReadEventsFromLog(fileDiff, previousFileSize, _server);
|
||||
|
||||
foreach (var gameEvent in events)
|
||||
{
|
||||
|
@ -28,7 +28,7 @@ namespace IW4MAdmin.Application.IO
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition)
|
||||
public async Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition, Server server = null)
|
||||
{
|
||||
// allocate the bytes for the new log lines
|
||||
List<string> logLines = new List<string>();
|
||||
|
@ -34,7 +34,7 @@ namespace IW4MAdmin.Application.IO
|
||||
|
||||
public int UpdateInterval => 500;
|
||||
|
||||
public async Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition)
|
||||
public async Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition, Server server = null)
|
||||
{
|
||||
var events = new List<GameEvent>();
|
||||
var response = await _logServerApi.Log(_safeLogPath, lastKey);
|
||||
|
157
Application/IO/NetworkGameLogReader.cs
Normal file
157
Application/IO/NetworkGameLogReader.cs
Normal file
@ -0,0 +1,157 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Integrations.Cod;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog.Context;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
|
||||
namespace IW4MAdmin.Application.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// provides capability of reading log files over udp
|
||||
/// </summary>
|
||||
class NetworkGameLogReader : IGameLogReader
|
||||
{
|
||||
private readonly IEventParser _eventParser;
|
||||
private readonly ILogger _logger;
|
||||
private readonly Uri _uri;
|
||||
private static readonly NetworkLogState State = new();
|
||||
private bool _stateRegistered;
|
||||
private CancellationToken _token;
|
||||
|
||||
public NetworkGameLogReader(IReadOnlyList<Uri> uris, IEventParser parser, ILogger<NetworkGameLogReader> logger)
|
||||
{
|
||||
_eventParser = parser;
|
||||
_uri = uris[0];
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public long Length => -1;
|
||||
|
||||
public int UpdateInterval => 150;
|
||||
|
||||
public Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition,
|
||||
Server server = null)
|
||||
{
|
||||
// todo: other games might support this
|
||||
var serverEndpoint = (server?.RemoteConnection as CodRConConnection)?.Endpoint;
|
||||
|
||||
if (serverEndpoint is null)
|
||||
{
|
||||
return Task.FromResult(Enumerable.Empty<GameEvent>());
|
||||
}
|
||||
|
||||
if (!_stateRegistered && !State.EndPointExists(serverEndpoint))
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = State.RegisterEndpoint(serverEndpoint, BuildLocalEndpoint()).Client;
|
||||
|
||||
_stateRegistered = true;
|
||||
_token = server.Manager.CancellationToken;
|
||||
|
||||
if (client == null)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogInformation("Not registering {Name} socket because it is already bound",
|
||||
nameof(NetworkGameLogReader));
|
||||
}
|
||||
return Task.FromResult(Enumerable.Empty<GameEvent>());
|
||||
}
|
||||
|
||||
new Thread(() => ReadNetworkData(client)).Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Could not register {Name} endpoint {Endpoint}",
|
||||
nameof(NetworkGameLogReader), _uri);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
var events = new List<GameEvent>();
|
||||
|
||||
foreach (var logData in State.GetServerLogData(serverEndpoint)
|
||||
.Select(log => Utilities.EncodingType.GetString(log)))
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(logData))
|
||||
{
|
||||
return Task.FromResult(Enumerable.Empty<GameEvent>());
|
||||
}
|
||||
|
||||
var lines = logData
|
||||
.Split('\n')
|
||||
.Where(line => line.Length > 0);
|
||||
|
||||
foreach (var eventLine in lines)
|
||||
{
|
||||
try
|
||||
{
|
||||
// this trim end should hopefully fix the nasty runaway regex
|
||||
var gameEvent = _eventParser.GenerateGameEvent(eventLine.TrimEnd('\r'));
|
||||
events.Add(gameEvent);
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Could not properly parse event line from http {EventLine}",
|
||||
eventLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Task.FromResult((IEnumerable<GameEvent>)events);
|
||||
}
|
||||
|
||||
private void ReadNetworkData(UdpClient client)
|
||||
{
|
||||
while (!_token.IsCancellationRequested)
|
||||
{
|
||||
// get more data
|
||||
IPEndPoint remoteEndpoint = null;
|
||||
byte[] bufferedData = null;
|
||||
|
||||
if (client == null)
|
||||
{
|
||||
// we already have a socket listening on this port for data, so we don't need to run another thread
|
||||
break;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
bufferedData = client.Receive(ref remoteEndpoint);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Could not receive lines for {LogReader}", nameof(NetworkGameLogReader));
|
||||
}
|
||||
|
||||
if (bufferedData != null)
|
||||
{
|
||||
State.QueueServerLogData(remoteEndpoint, bufferedData);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IPEndPoint BuildLocalEndpoint()
|
||||
{
|
||||
try
|
||||
{
|
||||
return new IPEndPoint(Dns.GetHostAddresses(_uri.Host).First(), _uri.Port);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Could not setup {LogReader} endpoint", nameof(NetworkGameLogReader));
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
138
Application/IO/NetworkLogState.cs
Normal file
138
Application/IO/NetworkLogState.cs
Normal file
@ -0,0 +1,138 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
|
||||
namespace IW4MAdmin.Application.IO;
|
||||
|
||||
public class NetworkLogState : Dictionary<IPEndPoint, UdpClientState>
|
||||
{
|
||||
public UdpClientState RegisterEndpoint(IPEndPoint serverEndpoint, IPEndPoint localEndpoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
if (!ContainsKey(serverEndpoint))
|
||||
{
|
||||
Add(serverEndpoint, new UdpClientState { Client = new UdpClient(localEndpoint) });
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
// we don't add the udp client because it already exists (listening to multiple servers from one socket)
|
||||
Add(serverEndpoint, new UdpClientState());
|
||||
}
|
||||
}
|
||||
|
||||
return this[serverEndpoint];
|
||||
}
|
||||
|
||||
|
||||
public List<byte[]> GetServerLogData(IPEndPoint serverEndpoint)
|
||||
{
|
||||
try
|
||||
{
|
||||
var state = this[serverEndpoint];
|
||||
|
||||
if (state == null)
|
||||
{
|
||||
return new List<byte[]>();
|
||||
}
|
||||
|
||||
// it's possible that we could be trying to read and write to the queue simultaneously so we need to wait
|
||||
this[serverEndpoint].OnAction.Wait();
|
||||
|
||||
var data = new List<byte[]>();
|
||||
|
||||
while (this[serverEndpoint].AvailableLogData.Count > 0)
|
||||
{
|
||||
data.Add(this[serverEndpoint].AvailableLogData.Dequeue());
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (this[serverEndpoint].OnAction.CurrentCount == 0)
|
||||
{
|
||||
this[serverEndpoint].OnAction.Release(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void QueueServerLogData(IPEndPoint serverEndpoint, byte[] data)
|
||||
{
|
||||
var endpoint = Keys.FirstOrDefault(key =>
|
||||
Equals(key.Address, serverEndpoint.Address) && key.Port == serverEndpoint.Port);
|
||||
|
||||
try
|
||||
{
|
||||
if (endpoint == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// currently our expected start and end characters
|
||||
var startsWithPrefix = StartsWith(data, "ÿÿÿÿprint\n");
|
||||
var endsWithDelimiter = data[^1] == '\n';
|
||||
|
||||
// we have the data we expected
|
||||
if (!startsWithPrefix || !endsWithDelimiter)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// it's possible that we could be trying to read and write to the queue simultaneously so we need to wait
|
||||
this[endpoint].OnAction.Wait();
|
||||
this[endpoint].AvailableLogData.Enqueue(data);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (endpoint != null && this[endpoint].OnAction.CurrentCount == 0)
|
||||
{
|
||||
this[endpoint].OnAction.Release(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool EndPointExists(IPEndPoint serverEndpoint)
|
||||
{
|
||||
lock (this)
|
||||
{
|
||||
return ContainsKey(serverEndpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool StartsWith(byte[] sourceArray, string match)
|
||||
{
|
||||
if (sourceArray is null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (match.Length > sourceArray.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return !match.Where((t, i) => sourceArray[i] != (byte)t).Any();
|
||||
}
|
||||
}
|
||||
|
||||
public class UdpClientState
|
||||
{
|
||||
public UdpClient Client { get; set; }
|
||||
public Queue<byte[]> AvailableLogData { get; } = new();
|
||||
public SemaphoreSlim OnAction { get; } = new(1, 1);
|
||||
|
||||
~UdpClientState()
|
||||
{
|
||||
OnAction.Dispose();
|
||||
Client?.Dispose();
|
||||
}
|
||||
}
|
@ -236,7 +236,7 @@ namespace IW4MAdmin
|
||||
private async Task CreatePluginTask(IPlugin plugin, GameEvent gameEvent)
|
||||
{
|
||||
// we don't want to run the events on parser plugins
|
||||
if (plugin is ScriptPlugin scriptPlugin && scriptPlugin.IsParser)
|
||||
if (plugin is ScriptPlugin { IsParser: true })
|
||||
{
|
||||
return;
|
||||
}
|
||||
@ -248,6 +248,11 @@ namespace IW4MAdmin
|
||||
{
|
||||
await plugin.OnEventAsync(gameEvent, this).WithWaitCancellation(tokenSource.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
ServerLogger.LogWarning("Timed out executing event {EventType} for {Plugin}", gameEvent.Type,
|
||||
plugin.Name);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(loc["SERVER_PLUGIN_ERROR"].FormatExt(plugin.Name, ex.GetType().Name));
|
||||
|
@ -68,6 +68,29 @@ namespace IW4MAdmin.Application.Misc
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task SetPersistentMeta(string metaKey, string metaValue, int clientId)
|
||||
{
|
||||
await AddPersistentMeta(metaKey, metaValue, new EFClient { ClientId = clientId });
|
||||
}
|
||||
|
||||
public async Task IncrementPersistentMeta(string metaKey, int incrementAmount, int clientId)
|
||||
{
|
||||
var existingMeta = await GetPersistentMeta(metaKey, new EFClient { ClientId = clientId });
|
||||
|
||||
if (!long.TryParse(existingMeta?.Value ?? "0", out var existingValue))
|
||||
{
|
||||
existingValue = 0;
|
||||
}
|
||||
|
||||
var newValue = existingValue + incrementAmount;
|
||||
await SetPersistentMeta(metaKey, newValue.ToString(), clientId);
|
||||
}
|
||||
|
||||
public async Task DecrementPersistentMeta(string metaKey, int decrementAmount, int clientId)
|
||||
{
|
||||
await IncrementPersistentMeta(metaKey, -decrementAmount, clientId);
|
||||
}
|
||||
|
||||
public async Task AddPersistentMeta(string metaKey, string metaValue)
|
||||
{
|
||||
await using var ctx = _contextFactory.CreateContext();
|
||||
|
@ -223,47 +223,49 @@ namespace IW4MAdmin.Application.Misc
|
||||
|
||||
public async Task OnEventAsync(GameEvent gameEvent, Server server)
|
||||
{
|
||||
if (_successfullyLoaded)
|
||||
if (!_successfullyLoaded)
|
||||
{
|
||||
try
|
||||
{
|
||||
await _onProcessing.WaitAsync();
|
||||
_scriptEngine.SetValue("_gameEvent", gameEvent);
|
||||
_scriptEngine.SetValue("_server", server);
|
||||
_scriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(server));
|
||||
_scriptEngine.Evaluate("plugin.onEventAsync(_gameEvent, _server)");
|
||||
}
|
||||
|
||||
catch (JavaScriptException ex)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} with event type {EventType} {@LocationInfo}",
|
||||
nameof(OnEventAsync), Path.GetFileName(_fileName), gameEvent.Type, ex.Location);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
try
|
||||
{
|
||||
await _onProcessing.WaitAsync();
|
||||
_scriptEngine.SetValue("_gameEvent", gameEvent);
|
||||
_scriptEngine.SetValue("_server", server);
|
||||
_scriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(server));
|
||||
_scriptEngine.Evaluate("plugin.onEventAsync(_gameEvent, _server)");
|
||||
}
|
||||
|
||||
catch (JavaScriptException ex)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} with event type {EventType} {@LocationInfo}",
|
||||
nameof(OnEventAsync), Path.GetFileName(_fileName), gameEvent.Type, ex.Location);
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Encountered error while running {MethodName} for script plugin {Plugin} with event type {EventType}",
|
||||
nameof(OnEventAsync), _fileName, gameEvent.Type);
|
||||
}
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
}
|
||||
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
catch (Exception ex)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Encountered error while running {MethodName} for script plugin {Plugin} with event type {EventType}",
|
||||
nameof(OnEventAsync), _fileName, gameEvent.Type);
|
||||
}
|
||||
|
||||
finally
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
}
|
||||
|
||||
finally
|
||||
{
|
||||
if (_onProcessing.CurrentCount == 0)
|
||||
{
|
||||
if (_onProcessing.CurrentCount == 0)
|
||||
{
|
||||
_onProcessing.Release(1);
|
||||
}
|
||||
_onProcessing.Release(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -11,13 +11,16 @@ init()
|
||||
level.eventBus.outVar = "sv_iw4madmin_out";
|
||||
level.eventBus.failKey = "fail";
|
||||
level.eventBus.timeoutKey = "timeout";
|
||||
level.eventBus.timeout = 10;
|
||||
level.eventBus.timeout = 30;
|
||||
|
||||
level.clientDataKey = "clientData";
|
||||
|
||||
level.eventTypes = spawnstruct();
|
||||
level.eventTypes.localClientEvent = "client_event";
|
||||
level.eventTypes.clientDataReceived = "ClientDataReceived";
|
||||
level.eventTypes.clientDataRequested = "ClientDataRequested";
|
||||
level.eventTypes.setClientDataRequested = "SetClientDataRequested";
|
||||
level.eventTypes.setClientDataCompleted = "SetClientDataCompleted";
|
||||
level.eventTypes.executeCommandRequested = "ExecuteCommandRequested";
|
||||
|
||||
SetDvarIfUninitialized( level.eventBus.inVar, "" );
|
||||
@ -27,11 +30,17 @@ init()
|
||||
|
||||
// map the event type to the handler
|
||||
level.eventCallbacks = [];
|
||||
level.eventCallbacks[level.eventTypes.clientDataReceived] = ::OnClientDataReceived;
|
||||
level.eventCallbacks[level.eventTypes.executeCommandRequested] = ::OnExecuteCommand;
|
||||
|
||||
level.eventCallbacks[level.eventTypes.clientDataReceived] = ::OnClientDataReceived;
|
||||
level.eventCallbacks[level.eventTypes.executeCommandRequested] = ::OnExecuteCommand;
|
||||
level.eventCallbacks[level.eventTypes.setClientDataCompleted] = ::OnSetClientDataCompleted;
|
||||
|
||||
if ( GetDvarInt( "sv_iw4madmin_integration_enabled" ) != 1 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// start long running tasks
|
||||
level thread PlayerWaitEvents();
|
||||
level thread MonitorClientEvents();
|
||||
level thread MonitorBus();
|
||||
level thread OnPlayerConnect();
|
||||
}
|
||||
@ -56,6 +65,7 @@ OnPlayerConnect()
|
||||
}
|
||||
|
||||
player thread OnPlayerSpawned();
|
||||
player thread PlayerTrackingOnInterval();
|
||||
}
|
||||
}
|
||||
|
||||
@ -70,17 +80,42 @@ OnPlayerSpawned()
|
||||
}
|
||||
}
|
||||
|
||||
OnPlayerDisconnect()
|
||||
{
|
||||
level endon ( "disconnect" );
|
||||
|
||||
for ( ;; )
|
||||
{
|
||||
self waittill( "disconnect" );
|
||||
self SaveTrackingMetrics();
|
||||
}
|
||||
}
|
||||
|
||||
OnGameEnded()
|
||||
{
|
||||
level endon ( "disconnect" );
|
||||
|
||||
for ( ;; )
|
||||
{
|
||||
level waittill( "game_ended" );
|
||||
// note: you can run data code here but it's possible for
|
||||
// data to get trucated, so we will try a timer based approach for now
|
||||
}
|
||||
}
|
||||
|
||||
DisplayWelcomeData()
|
||||
{
|
||||
self endon( "disconnect" );
|
||||
|
||||
clientData = self.pers[level.clientDataKey];
|
||||
|
||||
if ( clientData.permissionLevel != "User" )
|
||||
{
|
||||
self IPrintLnBold( "Welcome, your level is ^5" + clientData.permissionLevel );
|
||||
}
|
||||
wait (2.0);
|
||||
if ( clientData.permissionLevel == "User" || clientData.permissionLevel == "Flagged" )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
self IPrintLnBold( "Welcome, your level is ^5" + clientData.permissionLevel );
|
||||
wait( 2.0 );
|
||||
self IPrintLnBold( "You were last seen ^5" + clientData.lastConnection );
|
||||
}
|
||||
|
||||
@ -91,6 +126,7 @@ PlayerConnectEvents()
|
||||
clientData = self.pers[level.clientDataKey];
|
||||
|
||||
// this gives IW4MAdmin some time to register the player before making the request;
|
||||
// although probably not necessary some users might have a slow database or poll rate
|
||||
wait ( 2 );
|
||||
|
||||
if ( isDefined( clientData.state ) && clientData.state == "complete" )
|
||||
@ -103,14 +139,28 @@ PlayerConnectEvents()
|
||||
// self RequestClientMeta( "LastServerPlayed" );
|
||||
}
|
||||
|
||||
PlayerWaitEvents()
|
||||
PlayerTrackingOnInterval()
|
||||
{
|
||||
level endon( "game_ended" );
|
||||
self endon( "disconnect" );
|
||||
|
||||
for ( ;; )
|
||||
{
|
||||
wait ( 120 );
|
||||
if ( IsAlive( self ) )
|
||||
{
|
||||
self SaveTrackingMetrics();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MonitorClientEvents()
|
||||
{
|
||||
level endon( "disconnect" );
|
||||
self endon( "disconnect" );
|
||||
|
||||
for ( ;; )
|
||||
{
|
||||
level waittill( "client_event", client );
|
||||
level waittill( level.eventTypes.localClientEvent, client );
|
||||
|
||||
if ( level.iw4adminIntegrationDebug == 1 )
|
||||
{
|
||||
@ -135,16 +185,81 @@ PlayerWaitEvents()
|
||||
RequestClientMeta( metaKey )
|
||||
{
|
||||
getClientMetaEvent = BuildEventRequest( true, level.eventTypes.clientDataRequested, "Meta", self, metaKey );
|
||||
self thread QueueEvent( getClientMetaEvent, level.eventTypes.clientDataRequested );
|
||||
level thread QueueEvent( getClientMetaEvent, level.eventTypes.clientDataRequested, self );
|
||||
}
|
||||
|
||||
RequestClientBasicData()
|
||||
{
|
||||
getClientDataEvent = BuildEventRequest( true, level.eventTypes.clientDataRequested, "None", self, "" );
|
||||
self thread QueueEvent( getClientDataEvent, level.eventTypes.clientDataRequested );
|
||||
level thread QueueEvent( getClientDataEvent, level.eventTypes.clientDataRequested, self );
|
||||
}
|
||||
|
||||
BuildEventRequest( responseExpected, eventType, eventSubtype, client, data )
|
||||
IncrementClientMeta( metaKey, incrementValue, clientId )
|
||||
{
|
||||
SetClientMeta( metaKey, incrementValue, clientId, "increment" );
|
||||
}
|
||||
|
||||
DecrementClientMeta( metaKey, decrementValue, clientId )
|
||||
{
|
||||
SetClientMeta( metaKey, decrementValue, clientId, "decrement" );
|
||||
}
|
||||
|
||||
SetClientMeta( metaKey, metaValue, clientId, direction )
|
||||
{
|
||||
data = "key=" + metaKey + "|value=" + metaValue;
|
||||
clientNumber = -1;
|
||||
|
||||
if ( IsDefined ( clientId ) )
|
||||
{
|
||||
data = data + "|clientId=" + clientId;
|
||||
clientNumber = -1;
|
||||
}
|
||||
|
||||
if ( IsDefined( direction ) )
|
||||
{
|
||||
data = data + "|direction=" + direction;
|
||||
}
|
||||
|
||||
if ( IsPlayer( self ) )
|
||||
{
|
||||
clientNumber = self getEntityNumber();
|
||||
}
|
||||
|
||||
setClientMetaEvent = BuildEventRequest( true, level.eventTypes.setClientDataRequested, "Meta", clientNumber, data );
|
||||
level thread QueueEvent( setClientMetaEvent, level.eventTypes.setClientDataRequested, self );
|
||||
}
|
||||
|
||||
SaveTrackingMetrics()
|
||||
{
|
||||
if ( level.iw4adminIntegrationDebug == 1 )
|
||||
{
|
||||
self IPrintLn( "Saving tracking metrics for " + self.persistentClientId );
|
||||
}
|
||||
|
||||
currentShotCount = self getPlayerStat( "mostshotsfired" );
|
||||
change = currentShotCount - self.lastShotCount;
|
||||
self.lastShotCount = currentShotCount;
|
||||
|
||||
if ( level.iw4adminIntegrationDebug == 1 )
|
||||
{
|
||||
self IPrintLn( "Total Shots Fired increased by " + change );
|
||||
}
|
||||
|
||||
if ( !IsDefined( change ) )
|
||||
{
|
||||
change = 0;
|
||||
}
|
||||
|
||||
if ( change == 0 )
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
IncrementClientMeta( "TotalShotsFired", change, self.persistentClientId );
|
||||
|
||||
}
|
||||
|
||||
BuildEventRequest( responseExpected, eventType, eventSubtype, entOrId, data )
|
||||
{
|
||||
if ( !isDefined( data ) )
|
||||
{
|
||||
@ -155,6 +270,11 @@ BuildEventRequest( responseExpected, eventType, eventSubtype, client, data )
|
||||
{
|
||||
eventSubtype = "None";
|
||||
}
|
||||
|
||||
if ( IsPlayer( entOrId ) )
|
||||
{
|
||||
entOrId = entOrId getEntityNumber();
|
||||
}
|
||||
|
||||
request = "0";
|
||||
|
||||
@ -163,7 +283,7 @@ BuildEventRequest( responseExpected, eventType, eventSubtype, client, data )
|
||||
request = "1";
|
||||
}
|
||||
|
||||
request = request + ";" + eventType + ";" + eventSubtype + ";" + client getEntityNumber() + ";" + data;
|
||||
request = request + ";" + eventType + ";" + eventSubtype + ";" + entOrId + ";" + data;
|
||||
return request;
|
||||
}
|
||||
|
||||
@ -173,7 +293,7 @@ MonitorBus()
|
||||
|
||||
for( ;; )
|
||||
{
|
||||
wait ( 0.25 );
|
||||
wait ( 0.1 );
|
||||
|
||||
// check to see if IW4MAdmin is ready to receive more data
|
||||
if ( getDvar( level.eventBus.inVar ) == "" )
|
||||
@ -198,12 +318,12 @@ MonitorBus()
|
||||
}
|
||||
}
|
||||
|
||||
QueueEvent( request, eventType )
|
||||
QueueEvent( request, eventType, notifyEntity )
|
||||
{
|
||||
self endon( "disconnect" );
|
||||
|
||||
level endon( "disconnect" );
|
||||
|
||||
start = GetTime();
|
||||
maxWait = level.eventBus.timeout * 1000; // 10 seconds
|
||||
maxWait = level.eventBus.timeout * 1000; // 30 seconds
|
||||
timedOut = "";
|
||||
|
||||
while ( GetDvar( level.eventBus.inVar ) != "" && ( GetTime() - start ) < maxWait )
|
||||
@ -214,7 +334,7 @@ QueueEvent( request, eventType )
|
||||
{
|
||||
if ( level.iw4adminIntegrationDebug == 1 )
|
||||
{
|
||||
self IPrintLn( "A request is already in progress..." );
|
||||
IPrintLn( "A request is already in progress..." );
|
||||
}
|
||||
timedOut = "set";
|
||||
continue;
|
||||
@ -227,10 +347,13 @@ QueueEvent( request, eventType )
|
||||
{
|
||||
if ( level.iw4adminIntegrationDebug == 1 )
|
||||
{
|
||||
self IPrintLn( "Timed out waiting for response..." );
|
||||
IPrintLn( "Timed out waiting for response..." );
|
||||
}
|
||||
|
||||
NotifyClientEventTimeout( eventType );
|
||||
if ( IsDefined( notifyEntity) )
|
||||
{
|
||||
notifyEntity NotifyClientEventTimeout( eventType );
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
@ -287,7 +410,7 @@ NotifyClientEvent( eventInfo )
|
||||
|
||||
client.event = event;
|
||||
|
||||
level notify( "client_event", client );
|
||||
level notify( level.eventTypes.localClientEvent, client );
|
||||
}
|
||||
|
||||
//////////////////////////////////
|
||||
@ -311,20 +434,22 @@ OnClientDataReceived( event )
|
||||
|
||||
if ( event.subtype == "Meta" )
|
||||
{
|
||||
if ( !isDefined( clientData["meta"] ) )
|
||||
if ( !isDefined( clientData.meta ) )
|
||||
{
|
||||
clientData.meta = [];
|
||||
}
|
||||
|
||||
metaKey = event.data[0];
|
||||
clientData["meta"][metaKey] = event.data[metaKey];
|
||||
clientData.meta[metaKey] = event.data[metaKey];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
clientData.permissionLevel = event.data["level"];
|
||||
clientData.clientId = event.data["clientId"];
|
||||
clientData.lastConnection = event.data["lastConnection"];
|
||||
clientData.state = "complete";
|
||||
self.persistentClientId = event.data["clientId"];
|
||||
|
||||
self thread DisplayWelcomeData();
|
||||
}
|
||||
@ -355,6 +480,16 @@ OnExecuteCommand( event )
|
||||
}
|
||||
}
|
||||
|
||||
OnSetClientDataCompleted( event )
|
||||
{
|
||||
// IW4MAdmin let us know it persisted (success or fail)
|
||||
|
||||
if ( level.iw4adminIntegrationDebug == 1 )
|
||||
{
|
||||
IPrintLn( "Set Client Data -> subtype = " + event.subType + " status = " + event.data["status"] );
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////
|
||||
// Command Implementations
|
||||
/////////////////////////////////
|
||||
|
@ -13,6 +13,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
|
||||
version.txt = version.txt
|
||||
DeploymentFiles\UpdateIW4MAdmin.ps1 = DeploymentFiles\UpdateIW4MAdmin.ps1
|
||||
DeploymentFiles\UpdateIW4MAdmin.sh = DeploymentFiles\UpdateIW4MAdmin.sh
|
||||
GameFiles\IW4x\userraw\scripts\_integration.gsc = GameFiles\IW4x\userraw\scripts\_integration.gsc
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharedLibraryCore", "SharedLibraryCore\SharedLibraryCore.csproj", "{AA0541A2-8D51-4AD9-B0AC-3D1F5B162481}"
|
||||
|
@ -17,12 +17,16 @@ let plugin = {
|
||||
name: 'Game Interface',
|
||||
|
||||
onEventAsync: (gameEvent, server) => {
|
||||
const eventType = eventTypes[gameEvent.Type];
|
||||
|
||||
if (servers[server.EndPoint] != null && !servers[server.EndPoint].enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventType = eventTypes[gameEvent.Type];
|
||||
|
||||
if (eventType === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (eventType) {
|
||||
case 'start':
|
||||
const enabled = initialize(server);
|
||||
@ -33,7 +37,7 @@ let plugin = {
|
||||
break;
|
||||
case 'preconnect':
|
||||
// when the plugin is reloaded after the servers are started
|
||||
if (servers[server.EndPoint] == null) {
|
||||
if (servers[server.EndPoint] === undefined || servers[server.EndPoint] == null) {
|
||||
const enabled = initialize(server);
|
||||
|
||||
if (!enabled) {
|
||||
@ -45,11 +49,6 @@ let plugin = {
|
||||
timer.Start(0, pollRate);
|
||||
}
|
||||
break;
|
||||
case 'disconnect':
|
||||
if (server.ClientNum === 0 && servers[server.EndPoint] != null) {
|
||||
servers[server.EndPoint].timer.Stop();
|
||||
}
|
||||
break;
|
||||
case 'warn':
|
||||
const warningTitle = _localization.LocalizationIndex['GLOBAL_WARNING'];
|
||||
sendScriptCommand(server, 'Alert', gameEvent.Target, {
|
||||
@ -194,10 +193,10 @@ let commands = [{
|
||||
name: 'player',
|
||||
required: true
|
||||
},
|
||||
{
|
||||
name: 'message',
|
||||
required: true
|
||||
}],
|
||||
{
|
||||
name: 'message',
|
||||
required: true
|
||||
}],
|
||||
supportedGames: ['IW4'],
|
||||
// required
|
||||
execute: (gameEvent) => {
|
||||
@ -222,11 +221,11 @@ const sendEvent = (server, responseExpected, event, subtype, client, data) => {
|
||||
let pendingOut = true;
|
||||
let pendingCheckCount = 0;
|
||||
const start = new Date();
|
||||
|
||||
while (pendingOut && pendingCheckCount <= 30) {
|
||||
|
||||
while (pendingOut && pendingCheckCount <= 10) {
|
||||
try {
|
||||
const out = server.GetServerDvar(outDvar);
|
||||
pendingOut = !(out == null || out === '' || out === 'null');
|
||||
pendingOut = !(out == null || out === '' || out === 'null');
|
||||
} catch (error) {
|
||||
logger.WriteError(`Could not check server output dvar for IO status ${error}`);
|
||||
}
|
||||
@ -264,12 +263,17 @@ const parseEvent = (input) => {
|
||||
eventType: eventInfo[1],
|
||||
subType: eventInfo[2],
|
||||
clientNumber: eventInfo[3],
|
||||
data: eventInfo.length > 4 ? eventInfo [4] : undefined
|
||||
data: eventInfo.length > 4 ? parseDataString(eventInfo[4]) : undefined
|
||||
}
|
||||
}
|
||||
|
||||
const initialize = (server) => {
|
||||
const logger = _serviceResolver.ResolveService('ILogger');
|
||||
|
||||
servers[server.EndPoint] = {
|
||||
enabled: false
|
||||
}
|
||||
|
||||
let enabled = false;
|
||||
try {
|
||||
enabled = server.GetServerDvar('sv_iw4madmin_integration_enabled') === '1';
|
||||
@ -280,9 +284,6 @@ const initialize = (server) => {
|
||||
logger.WriteInfo(`GSC Integration enabled = ${enabled}`);
|
||||
|
||||
if (!enabled) {
|
||||
servers[server.EndPoint] = {
|
||||
enabled: false
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@ -293,10 +294,8 @@ const initialize = (server) => {
|
||||
// necessary to prevent multi-threaded access to the JS context
|
||||
timer.SetDependency(_lock);
|
||||
|
||||
servers[server.EndPoint] = {
|
||||
timer: timer,
|
||||
enabled: true
|
||||
}
|
||||
servers[server.EndPoint].timer = timer;
|
||||
servers[server.EndPoint].enabled = true;
|
||||
|
||||
try {
|
||||
server.SetServerDvar(inDvar, '');
|
||||
@ -328,6 +327,7 @@ const pollForEvents = server => {
|
||||
|
||||
logger.WriteDebug(`Processing input... ${event.eventType} ${event.subType} ${event.data} ${event.clientNumber}`);
|
||||
|
||||
// todo: refactor to mapping if possible
|
||||
if (event.eventType === 'ClientDataRequested') {
|
||||
const client = server.GetClientByNumber(event.clientNumber);
|
||||
|
||||
@ -338,11 +338,12 @@ const pollForEvents = server => {
|
||||
|
||||
if (event.subType === 'Meta') {
|
||||
const metaService = _serviceResolver.ResolveService('IMetaService');
|
||||
const meta = metaService.GetPersistentMeta(event.data, client).Result;
|
||||
const meta = metaService.GetPersistentMeta(event.data, client).GetAwaiter().GetResult();
|
||||
data[event.data] = meta === null ? '' : meta.Value;
|
||||
} else {
|
||||
data = {
|
||||
level: client.Level,
|
||||
clientId: client.ClientId,
|
||||
lastConnection: client.LastConnection
|
||||
};
|
||||
}
|
||||
@ -350,7 +351,42 @@ const pollForEvents = server => {
|
||||
sendEvent(server, false, 'ClientDataReceived', event.subType, client, data);
|
||||
} else {
|
||||
logger.WriteWarning(`Could not find client slot ${event.clientNumber} when processing ${event.eventType}`);
|
||||
sendEvent(server, false, 'ClientDataReceived', 'Fail', { ClientNumber: event.clientNumber }, undefined);
|
||||
sendEvent(server, false, 'ClientDataReceived', 'Fail', {ClientNumber: event.clientNumber}, undefined);
|
||||
}
|
||||
}
|
||||
|
||||
if (event.eventType === 'SetClientDataRequested') {
|
||||
let client = server.GetClientByNumber(event.clientNumber);
|
||||
let clientId;
|
||||
|
||||
if (client != null){
|
||||
clientId = client.ClientId;
|
||||
} else {
|
||||
clientId = parseInt(event.data.clientId);
|
||||
}
|
||||
|
||||
logger.WriteDebug(`ClientId=${clientId}`);
|
||||
|
||||
if (clientId == null) {
|
||||
logger.WriteWarning(`Could not find client slot ${event.clientNumber} when processing ${event.eventType}`);
|
||||
sendEvent(server, false, 'SetClientDataCompleted', 'Meta', {ClientNumber: event.clientNumber}, {status: 'Fail'});
|
||||
} else {
|
||||
if (event.subType === 'Meta') {
|
||||
const metaService = _serviceResolver.ResolveService('IMetaService');
|
||||
try {
|
||||
logger.WriteDebug(`Key=${event.data['key']}, Value=${event.data['value']}`);
|
||||
if (event.data['direction'] != null) {
|
||||
event.data['direction'] = 'up'
|
||||
? metaService.IncrementPersistentMeta(event.data['key'], event.data['value'], clientId).GetAwaiter().GetResult()
|
||||
: metaService.DecrementPersistentMeta(event.data['key'], event.data['value'], clientId).GetAwaiter().GetResult();
|
||||
} else {
|
||||
metaService.SetPersistentMeta(event.data['key'], event.data['value'], clientId).GetAwaiter().GetResult();
|
||||
}
|
||||
sendEvent(server, false, 'SetClientDataCompleted', 'Meta', {ClientNumber: event.clientNumber}, {status: 'Complete'});
|
||||
} catch (error) {
|
||||
sendEvent(server, false, 'SetClientDataCompleted', 'Meta', {ClientNumber: event.clientNumber}, {status: 'Fail'});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -360,6 +396,9 @@ const pollForEvents = server => {
|
||||
logger.WriteError(`Could not reset in bus value for ${server.EndPoint} - ${error}`);
|
||||
}
|
||||
}
|
||||
else if (server.ClientNum === 0) {
|
||||
servers[server.EndPoint].timer.Stop();
|
||||
}
|
||||
}
|
||||
|
||||
const buildDataString = data => {
|
||||
@ -375,3 +414,21 @@ const buildDataString = data => {
|
||||
|
||||
return formattedData.substring(0, Math.max(0, formattedData.length - 1));
|
||||
}
|
||||
|
||||
const parseDataString = data => {
|
||||
if (data === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const dict = {}
|
||||
|
||||
for (const segment of data.split('|')) {
|
||||
const keyValue = segment.split('=');
|
||||
if (keyValue.length !== 2) {
|
||||
continue;
|
||||
}
|
||||
dict[keyValue[0]] = keyValue[1];
|
||||
}
|
||||
|
||||
return dict.length === 0 ? data : dict;
|
||||
}
|
||||
|
@ -23,7 +23,8 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// </summary>
|
||||
/// <param name="fileSizeDiff"></param>
|
||||
/// <param name="startPosition"></param>
|
||||
/// <param name="server"></param>
|
||||
/// <returns></returns>
|
||||
Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition);
|
||||
Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition, Server server);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -19,6 +19,35 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <returns></returns>
|
||||
Task AddPersistentMeta(string metaKey, string metaValue, EFClient client, EFMeta linkedMeta = null);
|
||||
|
||||
/// <summary>
|
||||
/// adds or updates meta key and value to the database
|
||||
/// </summary>
|
||||
/// <param name="metaKey">key of meta data</param>
|
||||
/// <param name="metaValue">value of the meta data</param>
|
||||
/// <param name="clientId">id of the client to save the meta for</param>
|
||||
/// <returns></returns>
|
||||
Task SetPersistentMeta(string metaKey, string metaValue, int clientId);
|
||||
|
||||
/// <summary>
|
||||
/// increments meta value and persists to the database
|
||||
/// <remarks>if the meta value does not already exist it will be set to the increment amount</remarks>
|
||||
/// </summary>
|
||||
/// <param name="metaKey">key of meta data</param>
|
||||
/// <param name="incrementAmount">value to increment by</param>
|
||||
/// <param name="clientId">id of the client to save the meta for</param>
|
||||
/// <returns></returns>
|
||||
Task IncrementPersistentMeta(string metaKey, int incrementAmount, int clientId);
|
||||
|
||||
/// <summary>
|
||||
/// decrements meta value and persists to the database
|
||||
/// <remarks>if the meta value does not already exist it will be set to the decrement amount</remarks>
|
||||
/// </summary>
|
||||
/// <param name="metaKey">key of meta data</param>
|
||||
/// <param name="decrementAmount">value to increment by</param>
|
||||
/// <param name="clientId">id of the client to save the meta for</param>
|
||||
/// <returns></returns>
|
||||
Task DecrementPersistentMeta(string metaKey, int decrementAmount, int clientId);
|
||||
|
||||
/// <summary>
|
||||
/// adds or updates meta key and value to the database
|
||||
/// </summary>
|
||||
@ -82,4 +111,4 @@ namespace SharedLibraryCore.Interfaces
|
||||
Task<IEnumerable<T>> GetRuntimeMeta<T>(ClientPaginationRequest request, MetaType metaType)
|
||||
where T : IClientMeta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -390,17 +390,48 @@ namespace SharedLibraryCore
|
||||
|
||||
public string[] ExecuteServerCommand(string command)
|
||||
{
|
||||
return this.ExecuteCommandAsync(command).GetAwaiter().GetResult();
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
tokenSource.CancelAfter(TimeSpan.FromMilliseconds(400));
|
||||
|
||||
try
|
||||
{
|
||||
return this.ExecuteCommandAsync(command).WithWaitCancellation(tokenSource.Token).GetAwaiter().GetResult();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public string GetServerDvar(string dvarName)
|
||||
{
|
||||
return this.GetDvarAsync<string>(dvarName).GetAwaiter().GetResult()?.Value;
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
tokenSource.CancelAfter(TimeSpan.FromSeconds(400));
|
||||
try
|
||||
{
|
||||
return this.GetDvarAsync<string>(dvarName).WithWaitCancellation(tokenSource.Token).GetAwaiter()
|
||||
.GetResult()?.Value;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetServerDvar(string dvarName, string dvarValue)
|
||||
public bool SetServerDvar(string dvarName, string dvarValue)
|
||||
{
|
||||
this.SetDvarAsync(dvarName, dvarValue).GetAwaiter().GetResult();
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
tokenSource.CancelAfter(TimeSpan.FromSeconds(400));
|
||||
try
|
||||
{
|
||||
this.SetDvarAsync(dvarName, dvarValue).WithWaitCancellation(tokenSource.Token).GetAwaiter().GetResult();
|
||||
return true;
|
||||
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public EFClient GetClientByNumber(int clientNumber) =>
|
||||
|
@ -956,6 +956,19 @@ namespace SharedLibraryCore
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<T> WithWaitCancellation<T>(this Task<T> task,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var completedTask = await Task.WhenAny(task, Task.Delay(Timeout.Infinite, cancellationToken));
|
||||
if (completedTask == task)
|
||||
{
|
||||
return await task;
|
||||
}
|
||||
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
throw new InvalidOperationException("Infinite delay task completed.");
|
||||
}
|
||||
|
||||
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout)
|
||||
{
|
||||
await Task.WhenAny(task, Task.Delay(timeout));
|
||||
|
Reference in New Issue
Block a user