Compare commits
12 Commits
2022.02.02
...
2022.02.14
Author | SHA1 | Date | |
---|---|---|---|
037fac5786 | |||
f4b892d8f4 | |||
3640d1df54 | |||
f3c6b10a35 | |||
4dec284b31 | |||
c9cf7be341 | |||
aa6ae0ab8d | |||
12dfd8c558 | |||
07f675eadc | |||
576d7015fa | |||
b1a1aae6c0 | |||
a0f4ceccfe |
@ -24,7 +24,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="Jint" Version="3.0.0-beta-1632" />
|
<PackageReference Include="Jint" Version="3.0.0-beta-2037" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.1">
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.1">
|
||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
|
@ -236,13 +236,6 @@ namespace IW4MAdmin.Application
|
|||||||
.Select(ut => ut.Key)
|
.Select(ut => ut.Key)
|
||||||
.ToList();
|
.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
|
// remove the update tasks as they have completed
|
||||||
foreach (var serverId in serverTasksToRemove.Where(serverId => runningUpdateTasks.ContainsKey(serverId)))
|
foreach (var serverId in serverTasksToRemove.Where(serverId => runningUpdateTasks.ContainsKey(serverId)))
|
||||||
{
|
{
|
||||||
@ -419,7 +412,7 @@ namespace IW4MAdmin.Application
|
|||||||
|
|
||||||
if (!validationResult.IsValid)
|
if (!validationResult.IsValid)
|
||||||
{
|
{
|
||||||
throw new ConfigurationException("MANAGER_CONFIGURATION_ERROR")
|
throw new ConfigurationException(_translationLookup["MANAGER_CONFIGURATION_ERROR"])
|
||||||
{
|
{
|
||||||
Errors = validationResult.Errors.Select(_error => _error.ErrorMessage).ToArray(),
|
Errors = validationResult.Errors.Select(_error => _error.ErrorMessage).ToArray(),
|
||||||
ConfigurationFileName = ConfigHandler.FileName
|
ConfigurationFileName = ConfigHandler.FileName
|
||||||
@ -530,6 +523,7 @@ namespace IW4MAdmin.Application
|
|||||||
|
|
||||||
Console.WriteLine(_translationLookup["MANAGER_COMMUNICATION_INFO"]);
|
Console.WriteLine(_translationLookup["MANAGER_COMMUNICATION_INFO"]);
|
||||||
await InitializeServers();
|
await InitializeServers();
|
||||||
|
IsInitialized = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task InitializeServers()
|
private async Task InitializeServers()
|
||||||
|
@ -18,14 +18,22 @@ namespace IW4MAdmin.Application.Factories
|
|||||||
public IGameLogReader CreateGameLogReader(Uri[] logUris, IEventParser eventParser)
|
public IGameLogReader CreateGameLogReader(Uri[] logUris, IEventParser eventParser)
|
||||||
{
|
{
|
||||||
var baseUri = logUris[0];
|
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}\"");
|
throw new NotImplementedException($"No log reader implemented for Uri scheme \"{baseUri.Scheme}\"");
|
||||||
|
@ -6,6 +6,7 @@ using SharedLibraryCore.Interfaces;
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Threading.Tasks;
|
||||||
using Data.Models.Client;
|
using Data.Models.Client;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@ -30,7 +31,7 @@ namespace IW4MAdmin.Application.Factories
|
|||||||
|
|
||||||
/// <inheritdoc/>
|
/// <inheritdoc/>
|
||||||
public IManagerCommand CreateScriptCommand(string name, string alias, string description, string permission,
|
public IManagerCommand CreateScriptCommand(string name, string alias, string description, string permission,
|
||||||
bool isTargetRequired, IEnumerable<(string, bool)> args, Action<GameEvent> executeAction)
|
bool isTargetRequired, IEnumerable<(string, bool)> args, Func<GameEvent, Task> executeAction, Server.Game[] supportedGames)
|
||||||
{
|
{
|
||||||
var permissionEnum = Enum.Parse<EFClient.Permission>(permission);
|
var permissionEnum = Enum.Parse<EFClient.Permission>(permission);
|
||||||
var argsArray = args.Select(_arg => new CommandArgument
|
var argsArray = args.Select(_arg => new CommandArgument
|
||||||
@ -40,7 +41,7 @@ namespace IW4MAdmin.Application.Factories
|
|||||||
}).ToArray();
|
}).ToArray();
|
||||||
|
|
||||||
return new ScriptCommand(name, alias, description, isTargetRequired, permissionEnum, argsArray, executeAction,
|
return new ScriptCommand(name, alias, description, isTargetRequired, permissionEnum, argsArray, executeAction,
|
||||||
_config, _transLookup, _serviceProvider.GetRequiredService<ILogger<ScriptCommand>>());
|
_config, _transLookup, _serviceProvider.GetRequiredService<ILogger<ScriptCommand>>(), supportedGames);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,7 @@ namespace IW4MAdmin.Application.IO
|
|||||||
{
|
{
|
||||||
_reader = gameLogReaderFactory.CreateGameLogReader(gameLogUris, server.EventParser);
|
_reader = gameLogReaderFactory.CreateGameLogReader(gameLogUris, server.EventParser);
|
||||||
_server = server;
|
_server = server;
|
||||||
_ignoreBots = server?.Manager.GetApplicationSettings().Configuration().IgnoreBots ?? false;
|
_ignoreBots = server.Manager.GetApplicationSettings().Configuration()?.IgnoreBots ?? false;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,7 +69,7 @@ namespace IW4MAdmin.Application.IO
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var events = await _reader.ReadEventsFromLog(fileDiff, previousFileSize);
|
var events = await _reader.ReadEventsFromLog(fileDiff, previousFileSize, _server);
|
||||||
|
|
||||||
foreach (var gameEvent in events)
|
foreach (var gameEvent in events)
|
||||||
{
|
{
|
||||||
|
@ -28,7 +28,7 @@ namespace IW4MAdmin.Application.IO
|
|||||||
_logger = logger;
|
_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
|
// allocate the bytes for the new log lines
|
||||||
List<string> logLines = new List<string>();
|
List<string> logLines = new List<string>();
|
||||||
|
@ -34,7 +34,7 @@ namespace IW4MAdmin.Application.IO
|
|||||||
|
|
||||||
public int UpdateInterval => 500;
|
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 events = new List<GameEvent>();
|
||||||
var response = await _logServerApi.Log(_safeLogPath, lastKey);
|
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)
|
private async Task CreatePluginTask(IPlugin plugin, GameEvent gameEvent)
|
||||||
{
|
{
|
||||||
// we don't want to run the events on parser plugins
|
// 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;
|
return;
|
||||||
}
|
}
|
||||||
@ -248,6 +248,11 @@ namespace IW4MAdmin
|
|||||||
{
|
{
|
||||||
await plugin.OnEventAsync(gameEvent, this).WithWaitCancellation(tokenSource.Token);
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine(loc["SERVER_PLUGIN_ERROR"].FormatExt(plugin.Name, ex.GetType().Name));
|
Console.WriteLine(loc["SERVER_PLUGIN_ERROR"].FormatExt(plugin.Name, ex.GetType().Name));
|
||||||
|
@ -311,9 +311,9 @@ namespace IW4MAdmin.Application
|
|||||||
}
|
}
|
||||||
|
|
||||||
// register any script plugins
|
// register any script plugins
|
||||||
foreach (var scriptPlugin in pluginImporter.DiscoverScriptPlugins())
|
foreach (var plugin in pluginImporter.DiscoverScriptPlugins())
|
||||||
{
|
{
|
||||||
serviceCollection.AddSingleton(scriptPlugin);
|
serviceCollection.AddSingleton(plugin);
|
||||||
}
|
}
|
||||||
|
|
||||||
// register any eventable types
|
// register any eventable types
|
||||||
@ -435,6 +435,7 @@ namespace IW4MAdmin.Application
|
|||||||
.AddSingleton<IServerDataViewer, ServerDataViewer>()
|
.AddSingleton<IServerDataViewer, ServerDataViewer>()
|
||||||
.AddSingleton<IServerDataCollector, ServerDataCollector>()
|
.AddSingleton<IServerDataCollector, ServerDataCollector>()
|
||||||
.AddSingleton<IEventPublisher, EventPublisher>()
|
.AddSingleton<IEventPublisher, EventPublisher>()
|
||||||
|
.AddTransient<IScriptPluginTimerHelper, ScriptPluginTimerHelper>()
|
||||||
.AddSingleton(translationLookup)
|
.AddSingleton(translationLookup)
|
||||||
.AddDatabaseContextOptions(appConfig);
|
.AddDatabaseContextOptions(appConfig);
|
||||||
|
|
||||||
|
@ -68,6 +68,29 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
await ctx.SaveChangesAsync();
|
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)
|
public async Task AddPersistentMeta(string metaKey, string metaValue)
|
||||||
{
|
{
|
||||||
await using var ctx = _contextFactory.CreateContext();
|
await using var ctx = _contextFactory.CreateContext();
|
||||||
|
@ -6,6 +6,7 @@ using SharedLibraryCore.Interfaces;
|
|||||||
using System.Linq;
|
using System.Linq;
|
||||||
using SharedLibraryCore;
|
using SharedLibraryCore;
|
||||||
using IW4MAdmin.Application.API.Master;
|
using IW4MAdmin.Application.API.Master;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using SharedLibraryCore.Configuration;
|
using SharedLibraryCore.Configuration;
|
||||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||||
@ -39,24 +40,23 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public IEnumerable<IPlugin> DiscoverScriptPlugins()
|
public IEnumerable<IPlugin> DiscoverScriptPlugins()
|
||||||
{
|
{
|
||||||
string pluginDir = $"{Utilities.OperatingDirectory}{PLUGIN_DIR}{Path.DirectorySeparatorChar}";
|
var pluginDir = $"{Utilities.OperatingDirectory}{PLUGIN_DIR}{Path.DirectorySeparatorChar}";
|
||||||
|
|
||||||
if (Directory.Exists(pluginDir))
|
if (!Directory.Exists(pluginDir))
|
||||||
{
|
{
|
||||||
var scriptPluginFiles = Directory.GetFiles(pluginDir, "*.js").AsEnumerable().Union(GetRemoteScripts());
|
return Enumerable.Empty<IPlugin>();
|
||||||
|
}
|
||||||
|
|
||||||
_logger.LogDebug("Discovered {count} potential script plugins", scriptPluginFiles.Count());
|
var scriptPluginFiles =
|
||||||
|
Directory.GetFiles(pluginDir, "*.js").AsEnumerable().Union(GetRemoteScripts()).ToList();
|
||||||
|
|
||||||
if (scriptPluginFiles.Count() > 0)
|
_logger.LogDebug("Discovered {count} potential script plugins", scriptPluginFiles.Count);
|
||||||
{
|
|
||||||
foreach (string fileName in scriptPluginFiles)
|
return scriptPluginFiles.Select(fileName =>
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Discovered script plugin {fileName}", fileName);
|
_logger.LogDebug("Discovered script plugin {fileName}", fileName);
|
||||||
var plugin = new ScriptPlugin(_logger, fileName);
|
return new ScriptPlugin(_logger, fileName);
|
||||||
yield return plugin;
|
}).ToList();
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
@ -6,7 +6,6 @@ using System;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using Data.Models.Client;
|
using Data.Models.Client;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using static SharedLibraryCore.Database.Models.EFClient;
|
|
||||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||||
|
|
||||||
namespace IW4MAdmin.Application.Misc
|
namespace IW4MAdmin.Application.Misc
|
||||||
@ -16,14 +15,15 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public class ScriptCommand : Command
|
public class ScriptCommand : Command
|
||||||
{
|
{
|
||||||
private readonly Action<GameEvent> _executeAction;
|
private readonly Func<GameEvent, Task> _executeAction;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
public ScriptCommand(string name, string alias, string description, bool isTargetRequired, EFClient.Permission permission,
|
public ScriptCommand(string name, string alias, string description, bool isTargetRequired,
|
||||||
CommandArgument[] args, Action<GameEvent> executeAction, CommandConfiguration config, ITranslationLookup layout, ILogger<ScriptCommand> logger)
|
EFClient.Permission permission,
|
||||||
|
CommandArgument[] args, Func<GameEvent, Task> executeAction, CommandConfiguration config,
|
||||||
|
ITranslationLookup layout, ILogger<ScriptCommand> logger, Server.Game[] supportedGames)
|
||||||
: base(config, layout)
|
: base(config, layout)
|
||||||
{
|
{
|
||||||
|
|
||||||
_executeAction = executeAction;
|
_executeAction = executeAction;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
Name = name;
|
Name = name;
|
||||||
@ -32,6 +32,7 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
RequiresTarget = isTargetRequired;
|
RequiresTarget = isTargetRequired;
|
||||||
Permission = permission;
|
Permission = permission;
|
||||||
Arguments = args;
|
Arguments = args;
|
||||||
|
SupportedGames = supportedGames;
|
||||||
}
|
}
|
||||||
|
|
||||||
public override async Task ExecuteAsync(GameEvent e)
|
public override async Task ExecuteAsync(GameEvent e)
|
||||||
@ -43,7 +44,7 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
await Task.Run(() => _executeAction(e));
|
await _executeAction(e);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
@ -13,6 +13,7 @@ using System.Linq;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Threading;
|
using System.Threading;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
using Jint.Runtime.Interop;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using Serilog.Context;
|
using Serilog.Context;
|
||||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||||
@ -36,12 +37,12 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
public bool IsParser { get; private set; }
|
public bool IsParser { get; private set; }
|
||||||
|
|
||||||
public FileSystemWatcher Watcher { get; private set; }
|
public FileSystemWatcher Watcher { get; }
|
||||||
|
|
||||||
private Engine _scriptEngine;
|
private Engine _scriptEngine;
|
||||||
private readonly string _fileName;
|
private readonly string _fileName;
|
||||||
private readonly SemaphoreSlim _onProcessing;
|
private readonly SemaphoreSlim _onProcessing = new(1, 1);
|
||||||
private bool successfullyLoaded;
|
private bool _successfullyLoaded;
|
||||||
private readonly List<string> _registeredCommandNames;
|
private readonly List<string> _registeredCommandNames;
|
||||||
private readonly ILogger _logger;
|
private readonly ILogger _logger;
|
||||||
|
|
||||||
@ -49,15 +50,14 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
{
|
{
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
_fileName = filename;
|
_fileName = filename;
|
||||||
Watcher = new FileSystemWatcher()
|
Watcher = new FileSystemWatcher
|
||||||
{
|
{
|
||||||
Path = workingDirectory == null ? $"{Utilities.OperatingDirectory}Plugins{Path.DirectorySeparatorChar}" : workingDirectory,
|
Path = workingDirectory ?? $"{Utilities.OperatingDirectory}Plugins{Path.DirectorySeparatorChar}",
|
||||||
NotifyFilter = NotifyFilters.Size,
|
NotifyFilter = NotifyFilters.Size,
|
||||||
Filter = _fileName.Split(Path.DirectorySeparatorChar).Last()
|
Filter = _fileName.Split(Path.DirectorySeparatorChar).Last()
|
||||||
};
|
};
|
||||||
|
|
||||||
Watcher.EnableRaisingEvents = true;
|
Watcher.EnableRaisingEvents = true;
|
||||||
_onProcessing = new SemaphoreSlim(1, 1);
|
|
||||||
_registeredCommandNames = new List<string>();
|
_registeredCommandNames = new List<string>();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,12 +67,13 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
_onProcessing.Dispose();
|
_onProcessing.Dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task Initialize(IManager manager, IScriptCommandFactory scriptCommandFactory, IScriptPluginServiceResolver serviceResolver)
|
public async Task Initialize(IManager manager, IScriptCommandFactory scriptCommandFactory,
|
||||||
|
IScriptPluginServiceResolver serviceResolver)
|
||||||
|
{
|
||||||
|
try
|
||||||
{
|
{
|
||||||
await _onProcessing.WaitAsync();
|
await _onProcessing.WaitAsync();
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
// for some reason we get an event trigger when the file is not finished being modified.
|
// for some reason we get an event trigger when the file is not finished being modified.
|
||||||
// this must have been a change in .NET CORE 3.x
|
// this must have been a change in .NET CORE 3.x
|
||||||
// so if the new file is empty we can't process it yet
|
// so if the new file is empty we can't process it yet
|
||||||
@ -81,26 +82,27 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool firstRun = _scriptEngine == null;
|
var firstRun = _scriptEngine == null;
|
||||||
|
|
||||||
// it's been loaded before so we need to call the unload event
|
// it's been loaded before so we need to call the unload event
|
||||||
if (!firstRun)
|
if (!firstRun)
|
||||||
{
|
{
|
||||||
await OnUnloadAsync();
|
await OnUnloadAsync();
|
||||||
|
|
||||||
foreach (string commandName in _registeredCommandNames)
|
foreach (var commandName in _registeredCommandNames)
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Removing plugin registered command {command}", commandName);
|
_logger.LogDebug("Removing plugin registered command {Command}", commandName);
|
||||||
manager.RemoveCommandByName(commandName);
|
manager.RemoveCommandByName(commandName);
|
||||||
}
|
}
|
||||||
|
|
||||||
_registeredCommandNames.Clear();
|
_registeredCommandNames.Clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
successfullyLoaded = false;
|
_successfullyLoaded = false;
|
||||||
string script;
|
string script;
|
||||||
|
|
||||||
using (var stream = new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
await using (var stream =
|
||||||
|
new FileStream(_fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
|
||||||
{
|
{
|
||||||
using (var reader = new StreamReader(stream, Encoding.Default))
|
using (var reader = new StreamReader(stream, Encoding.Default))
|
||||||
{
|
{
|
||||||
@ -116,39 +118,28 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
typeof(Utilities).Assembly,
|
typeof(Utilities).Assembly,
|
||||||
typeof(Encoding).Assembly
|
typeof(Encoding).Assembly
|
||||||
})
|
})
|
||||||
.CatchClrExceptions());
|
.CatchClrExceptions()
|
||||||
|
.AddObjectConverter(new PermissionLevelToStringConverter()));
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
_scriptEngine.Execute(script);
|
_scriptEngine.Execute(script);
|
||||||
}
|
|
||||||
catch (JavaScriptException ex)
|
|
||||||
{
|
|
||||||
|
|
||||||
_logger.LogError(ex,
|
|
||||||
"Encountered JavaScript runtime error while executing {methodName} for script plugin {plugin} at {@locationInfo}",
|
|
||||||
nameof(Initialize), _fileName, ex.Location);
|
|
||||||
throw new PluginException($"A JavaScript parsing error occured while initializing script plugin");
|
|
||||||
}
|
|
||||||
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
|
|
||||||
_logger.LogError(e,
|
|
||||||
"Encountered unexpected error while running {methodName} for script plugin {plugin}",
|
|
||||||
nameof(Initialize), _fileName);
|
|
||||||
throw new PluginException($"An unexpected error occured while initialization script plugin");
|
|
||||||
}
|
|
||||||
|
|
||||||
_scriptEngine.SetValue("_localization", Utilities.CurrentLocalization);
|
_scriptEngine.SetValue("_localization", Utilities.CurrentLocalization);
|
||||||
_scriptEngine.SetValue("_serviceResolver", serviceResolver);
|
_scriptEngine.SetValue("_serviceResolver", serviceResolver);
|
||||||
dynamic pluginObject = _scriptEngine.GetValue("plugin").ToObject();
|
_scriptEngine.SetValue("_lock", _onProcessing);
|
||||||
|
dynamic pluginObject = _scriptEngine.Evaluate("plugin").ToObject();
|
||||||
|
|
||||||
Author = pluginObject.author;
|
Author = pluginObject.author;
|
||||||
Name = pluginObject.name;
|
Name = pluginObject.name;
|
||||||
Version = (float)pluginObject.version;
|
Version = (float)pluginObject.version;
|
||||||
|
|
||||||
var commands = _scriptEngine.GetValue("commands");
|
var commands = JsValue.Undefined;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
commands = _scriptEngine.Evaluate("commands");
|
||||||
|
}
|
||||||
|
catch (JavaScriptException)
|
||||||
|
{
|
||||||
|
// ignore because commands aren't defined;
|
||||||
|
}
|
||||||
|
|
||||||
if (commands != JsValue.Undefined)
|
if (commands != JsValue.Undefined)
|
||||||
{
|
{
|
||||||
@ -156,7 +147,7 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
{
|
{
|
||||||
foreach (var command in GenerateScriptCommands(commands, scriptCommandFactory))
|
foreach (var command in GenerateScriptCommands(commands, scriptCommandFactory))
|
||||||
{
|
{
|
||||||
_logger.LogDebug("Adding plugin registered command {commandName}", command.Name);
|
_logger.LogDebug("Adding plugin registered command {CommandName}", command.Name);
|
||||||
manager.AddAdditionalCommand(command);
|
manager.AddAdditionalCommand(command);
|
||||||
_registeredCommandNames.Add(command.Name);
|
_registeredCommandNames.Add(command.Name);
|
||||||
}
|
}
|
||||||
@ -164,7 +155,8 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
|
|
||||||
catch (RuntimeBinderException e)
|
catch (RuntimeBinderException e)
|
||||||
{
|
{
|
||||||
throw new PluginException($"Not all required fields were found: {e.Message}") { PluginFile = _fileName };
|
throw new PluginException($"Not all required fields were found: {e.Message}")
|
||||||
|
{ PluginFile = _fileName };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -174,8 +166,8 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
{
|
{
|
||||||
await OnLoadAsync(manager);
|
await OnLoadAsync(manager);
|
||||||
IsParser = true;
|
IsParser = true;
|
||||||
var eventParser = (IEventParser)_scriptEngine.GetValue("eventParser").ToObject();
|
var eventParser = (IEventParser)_scriptEngine.Evaluate("eventParser").ToObject();
|
||||||
var rconParser = (IRConParser)_scriptEngine.GetValue("rconParser").ToObject();
|
var rconParser = (IRConParser)_scriptEngine.Evaluate("rconParser").ToObject();
|
||||||
manager.AdditionalEventParsers.Add(eventParser);
|
manager.AdditionalEventParsers.Add(eventParser);
|
||||||
manager.AdditionalRConParsers.Add(rconParser);
|
manager.AdditionalRConParsers.Add(rconParser);
|
||||||
}
|
}
|
||||||
@ -194,25 +186,79 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
await OnLoadAsync(manager);
|
await OnLoadAsync(manager);
|
||||||
}
|
}
|
||||||
|
|
||||||
successfullyLoaded = true;
|
_successfullyLoaded = true;
|
||||||
|
}
|
||||||
|
catch (JavaScriptException ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} at {@LocationInfo}",
|
||||||
|
nameof(Initialize), Path.GetFileName(_fileName), ex.Location);
|
||||||
|
|
||||||
|
throw new PluginException("An error occured while initializing script plugin");
|
||||||
|
}
|
||||||
|
catch (Exception ex) when (ex.InnerException is JavaScriptException jsEx)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} initialization {@LocationInfo}",
|
||||||
|
nameof(Initialize), _fileName, jsEx.Location);
|
||||||
|
|
||||||
|
throw new PluginException("An error occured while initializing script plugin");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin}",
|
||||||
|
nameof(OnLoadAsync), Path.GetFileName(_fileName));
|
||||||
|
|
||||||
|
throw new PluginException("An error occured while executing action for script plugin");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (_onProcessing.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
_onProcessing.Release(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task OnEventAsync(GameEvent gameEvent, Server server)
|
||||||
|
{
|
||||||
|
if (!_successfullyLoaded)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
catch (JavaScriptException ex)
|
||||||
|
{
|
||||||
|
using (LogContext.PushProperty("Server", server.ToString()))
|
||||||
{
|
{
|
||||||
_logger.LogError(ex,
|
_logger.LogError(ex,
|
||||||
"Encountered JavaScript runtime error while executing {methodName} for script plugin {plugin} initialization {@locationInfo}",
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} with event type {EventType} {@LocationInfo}",
|
||||||
nameof(OnLoadAsync), _fileName, ex.Location);
|
nameof(OnEventAsync), Path.GetFileName(_fileName), gameEvent.Type, ex.Location);
|
||||||
|
}
|
||||||
|
|
||||||
throw new PluginException("An error occured while initializing script plugin");
|
throw new PluginException("An error occured while executing action for script plugin");
|
||||||
}
|
}
|
||||||
|
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
using (LogContext.PushProperty("Server", server.ToString()))
|
||||||
{
|
{
|
||||||
_logger.LogError(ex,
|
_logger.LogError(ex,
|
||||||
"Encountered unexpected error while running {methodName} for script plugin {plugin}",
|
"Encountered error while running {MethodName} for script plugin {Plugin} with event type {EventType}",
|
||||||
nameof(OnLoadAsync), _fileName);
|
nameof(OnEventAsync), _fileName, gameEvent.Type);
|
||||||
|
}
|
||||||
|
|
||||||
throw new PluginException("An unexpected error occured while initializing script plugin");
|
throw new PluginException("An error occured while executing action for script plugin");
|
||||||
}
|
}
|
||||||
|
|
||||||
finally
|
finally
|
||||||
@ -224,73 +270,69 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task OnEventAsync(GameEvent E, Server S)
|
public Task OnLoadAsync(IManager manager)
|
||||||
{
|
{
|
||||||
if (successfullyLoaded)
|
try
|
||||||
{
|
{
|
||||||
await _onProcessing.WaitAsync();
|
_logger.LogDebug("OnLoad executing for {Name}", Name);
|
||||||
|
_scriptEngine.SetValue("_manager", manager);
|
||||||
|
_scriptEngine.Evaluate("plugin.onLoadAsync(_manager)");
|
||||||
|
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
catch (JavaScriptException ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} at {@LocationInfo}",
|
||||||
|
nameof(OnLoadAsync), Path.GetFileName(_fileName), ex.Location);
|
||||||
|
|
||||||
|
throw new PluginException("A runtime error occured while executing action for script plugin");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin}",
|
||||||
|
nameof(OnLoadAsync), Path.GetFileName(_fileName));
|
||||||
|
|
||||||
|
throw new PluginException("An error occured while executing action for script plugin");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task OnTickAsync(Server server)
|
||||||
|
{
|
||||||
|
_scriptEngine.SetValue("_server", server);
|
||||||
|
await Task.FromResult(_scriptEngine.Evaluate("plugin.onTickAsync(_server)"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task OnUnloadAsync()
|
||||||
|
{
|
||||||
|
if (!_successfullyLoaded)
|
||||||
|
{
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_scriptEngine.SetValue("_gameEvent", E);
|
_scriptEngine.Evaluate("plugin.onUnloadAsync()");
|
||||||
_scriptEngine.SetValue("_server", S);
|
|
||||||
_scriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(S));
|
|
||||||
_scriptEngine.Execute("plugin.onEventAsync(_gameEvent, _server)").GetCompletionValue();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
catch (JavaScriptException ex)
|
catch (JavaScriptException ex)
|
||||||
{
|
{
|
||||||
using (LogContext.PushProperty("Server", S.ToString()))
|
_logger.LogError(ex,
|
||||||
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} at {@LocationInfo}",
|
||||||
|
nameof(OnUnloadAsync), Path.GetFileName(_fileName), ex.Location);
|
||||||
|
|
||||||
|
throw new PluginException("A runtime error occured while executing action for script plugin");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex,
|
_logger.LogError(ex,
|
||||||
"Encountered JavaScript runtime error while executing {methodName} for script plugin {plugin} with event type {eventType} {@locationInfo}",
|
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin}",
|
||||||
nameof(OnEventAsync), _fileName, E.Type, ex.Location);
|
nameof(OnUnloadAsync), Path.GetFileName(_fileName));
|
||||||
|
|
||||||
|
throw new PluginException("An error occured while executing action for script plugin");
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new PluginException($"An error occured while executing action for script plugin");
|
return Task.CompletedTask;
|
||||||
}
|
|
||||||
|
|
||||||
catch (Exception e)
|
|
||||||
{
|
|
||||||
using (LogContext.PushProperty("Server", S.ToString()))
|
|
||||||
{
|
|
||||||
_logger.LogError(e,
|
|
||||||
"Encountered unexpected error while running {methodName} for script plugin {plugin} with event type {eventType}",
|
|
||||||
nameof(OnEventAsync), _fileName, E.Type);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new PluginException($"An error occured while executing action for script plugin");
|
|
||||||
}
|
|
||||||
|
|
||||||
finally
|
|
||||||
{
|
|
||||||
if (_onProcessing.CurrentCount == 0)
|
|
||||||
{
|
|
||||||
_onProcessing.Release(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task OnLoadAsync(IManager manager)
|
|
||||||
{
|
|
||||||
_logger.LogDebug("OnLoad executing for {name}", Name);
|
|
||||||
_scriptEngine.SetValue("_manager", manager);
|
|
||||||
await Task.FromResult(_scriptEngine.Execute("plugin.onLoadAsync(_manager)").GetCompletionValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task OnTickAsync(Server S)
|
|
||||||
{
|
|
||||||
_scriptEngine.SetValue("_server", S);
|
|
||||||
await Task.FromResult(_scriptEngine.Execute("plugin.onTickAsync(_server)").GetCompletionValue());
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task OnUnloadAsync()
|
|
||||||
{
|
|
||||||
if (successfullyLoaded)
|
|
||||||
{
|
|
||||||
await Task.FromResult(_scriptEngine.Execute("plugin.onUnloadAsync()").GetCompletionValue());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -299,9 +341,9 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
/// <param name="commands">commands value from jint parser</param>
|
/// <param name="commands">commands value from jint parser</param>
|
||||||
/// <param name="scriptCommandFactory">factory to create the command from</param>
|
/// <param name="scriptCommandFactory">factory to create the command from</param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public IEnumerable<IManagerCommand> GenerateScriptCommands(JsValue commands, IScriptCommandFactory scriptCommandFactory)
|
private IEnumerable<IManagerCommand> GenerateScriptCommands(JsValue commands, IScriptCommandFactory scriptCommandFactory)
|
||||||
{
|
{
|
||||||
List<IManagerCommand> commandList = new List<IManagerCommand>();
|
var commandList = new List<IManagerCommand>();
|
||||||
|
|
||||||
// go through each defined command
|
// go through each defined command
|
||||||
foreach (var command in commands.AsArray())
|
foreach (var command in commands.AsArray())
|
||||||
@ -311,9 +353,10 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
string alias = dynamicCommand.alias;
|
string alias = dynamicCommand.alias;
|
||||||
string description = dynamicCommand.description;
|
string description = dynamicCommand.description;
|
||||||
string permission = dynamicCommand.permission;
|
string permission = dynamicCommand.permission;
|
||||||
bool targetRequired = false;
|
List<Server.Game> supportedGames = null;
|
||||||
|
var targetRequired = false;
|
||||||
|
|
||||||
List<(string, bool)> args = new List<(string, bool)>();
|
var args = new List<(string, bool)>();
|
||||||
dynamic arguments = null;
|
dynamic arguments = null;
|
||||||
|
|
||||||
try
|
try
|
||||||
@ -344,26 +387,85 @@ namespace IW4MAdmin.Application.Misc
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void execute(GameEvent e)
|
|
||||||
{
|
|
||||||
_scriptEngine.SetValue("_event", e);
|
|
||||||
var jsEventObject = _scriptEngine.GetValue("_event");
|
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
dynamicCommand.execute.Target.Invoke(jsEventObject);
|
foreach (var game in dynamicCommand.supportedGames)
|
||||||
|
{
|
||||||
|
supportedGames ??= new List<Server.Game>();
|
||||||
|
supportedGames.Add(Enum.Parse(typeof(Server.Game), game.ToString()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (RuntimeBinderException)
|
||||||
|
{
|
||||||
|
// supported games is optional
|
||||||
|
}
|
||||||
|
|
||||||
|
async Task Execute(GameEvent gameEvent)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await _onProcessing.WaitAsync();
|
||||||
|
|
||||||
|
_scriptEngine.SetValue("_event", gameEvent);
|
||||||
|
var jsEventObject = _scriptEngine.Evaluate("_event");
|
||||||
|
|
||||||
|
dynamicCommand.execute.Target.Invoke(_scriptEngine, jsEventObject);
|
||||||
}
|
}
|
||||||
|
|
||||||
catch (JavaScriptException ex)
|
catch (JavaScriptException ex)
|
||||||
{
|
{
|
||||||
throw new PluginException($"An error occured while executing action for script plugin: {ex.Error} (Line: {ex.Location.Start.Line}, Character: {ex.Location.Start.Column})") { PluginFile = _fileName };
|
using (LogContext.PushProperty("Server", gameEvent.Owner?.ToString()))
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Could not execute command action for {Filename} {@Location}",
|
||||||
|
Path.GetFileName(_fileName), ex.Location);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new PluginException("A runtime error occured while executing action for script plugin");
|
||||||
|
}
|
||||||
|
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
using (LogContext.PushProperty("Server", gameEvent.Owner?.ToString()))
|
||||||
|
{
|
||||||
|
_logger.LogError(ex,
|
||||||
|
"Could not execute command action for script plugin {FileName}",
|
||||||
|
Path.GetFileName(_fileName));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new PluginException("An error occured while executing action for script plugin");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (_onProcessing.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
_onProcessing.Release(1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
commandList.Add(scriptCommandFactory.CreateScriptCommand(name, alias, description, permission, targetRequired, args, execute));
|
commandList.Add(scriptCommandFactory.CreateScriptCommand(name, alias, description, permission,
|
||||||
|
targetRequired, args, Execute, supportedGames?.ToArray()));
|
||||||
}
|
}
|
||||||
|
|
||||||
return commandList;
|
return commandList;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public class PermissionLevelToStringConverter : IObjectConverter
|
||||||
|
{
|
||||||
|
public bool TryConvert(Engine engine, object value, out JsValue result)
|
||||||
|
{
|
||||||
|
if (value is Data.Models.Client.EFClient.Permission)
|
||||||
|
{
|
||||||
|
result = value.ToString();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
result = JsValue.Null;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
159
Application/Misc/ScriptPluginTimerHelper.cs
Normal file
159
Application/Misc/ScriptPluginTimerHelper.cs
Normal file
@ -0,0 +1,159 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
using Jint.Native;
|
||||||
|
using Jint.Runtime;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using SharedLibraryCore.Interfaces;
|
||||||
|
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||||
|
|
||||||
|
namespace IW4MAdmin.Application.Misc;
|
||||||
|
|
||||||
|
public class ScriptPluginTimerHelper : IScriptPluginTimerHelper
|
||||||
|
{
|
||||||
|
private Timer _timer;
|
||||||
|
private Action _actions;
|
||||||
|
private Delegate _jsAction;
|
||||||
|
private string _actionName;
|
||||||
|
private const int DefaultDelay = 0;
|
||||||
|
private const int DefaultInterval = 1000;
|
||||||
|
private readonly ILogger _logger;
|
||||||
|
private readonly ManualResetEventSlim _onRunningTick = new();
|
||||||
|
private SemaphoreSlim _onDependentAction;
|
||||||
|
|
||||||
|
public ScriptPluginTimerHelper(ILogger<ScriptPluginTimerHelper> logger)
|
||||||
|
{
|
||||||
|
_logger = logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
~ScriptPluginTimerHelper()
|
||||||
|
{
|
||||||
|
if (_timer != null)
|
||||||
|
{
|
||||||
|
Stop();
|
||||||
|
}
|
||||||
|
_onRunningTick.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start(int delay, int interval)
|
||||||
|
{
|
||||||
|
if (_actions is null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException("Timer action must be defined before starting");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (delay < 0)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Timer delay must be >= 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (interval < 20)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("Timer interval must be at least 20ms");
|
||||||
|
}
|
||||||
|
|
||||||
|
Stop();
|
||||||
|
|
||||||
|
_logger.LogDebug("Starting script timer...");
|
||||||
|
|
||||||
|
_onRunningTick.Set();
|
||||||
|
_timer ??= new Timer(callback => _actions(), null, delay, interval);
|
||||||
|
IsRunning = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start(int interval)
|
||||||
|
{
|
||||||
|
Start(DefaultDelay, interval);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Start()
|
||||||
|
{
|
||||||
|
Start(DefaultDelay, DefaultInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Stop()
|
||||||
|
{
|
||||||
|
if (_timer == null)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogDebug("Stopping script timer...");
|
||||||
|
_timer.Change(Timeout.Infinite, Timeout.Infinite);
|
||||||
|
_timer.Dispose();
|
||||||
|
_timer = null;
|
||||||
|
IsRunning = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void OnTick(Delegate action, string actionName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(actionName))
|
||||||
|
{
|
||||||
|
throw new ArgumentException("actionName must be provided", nameof(actionName));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action is null)
|
||||||
|
{
|
||||||
|
throw new ArgumentException("action must be provided", nameof(action));
|
||||||
|
}
|
||||||
|
|
||||||
|
_logger.LogDebug("Adding new action with name {ActionName}", actionName);
|
||||||
|
|
||||||
|
_jsAction = action;
|
||||||
|
_actionName = actionName;
|
||||||
|
_actions = OnTick;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ReleaseThreads()
|
||||||
|
{
|
||||||
|
_onRunningTick.Set();
|
||||||
|
|
||||||
|
if (_onDependentAction?.CurrentCount != 0)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_onDependentAction?.Release(1);
|
||||||
|
}
|
||||||
|
private void OnTick()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!_onRunningTick.IsSet)
|
||||||
|
{
|
||||||
|
_logger.LogDebug("Previous {OnTick} is still running, so we are skipping this one",
|
||||||
|
nameof(OnTick));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_onRunningTick.Reset();
|
||||||
|
|
||||||
|
// the js engine is not thread safe so we need to ensure we're not executing OnTick and OnEventAsync simultaneously
|
||||||
|
_onDependentAction?.WaitAsync().Wait();
|
||||||
|
var start = DateTime.Now;
|
||||||
|
_jsAction.DynamicInvoke(JsValue.Undefined, new[] { JsValue.Undefined });
|
||||||
|
_logger.LogDebug("OnTick took {Time}ms", (DateTime.Now - start).TotalMilliseconds);
|
||||||
|
ReleaseThreads();
|
||||||
|
}
|
||||||
|
|
||||||
|
catch (Exception ex) when (ex.InnerException is JavaScriptException jsex)
|
||||||
|
{
|
||||||
|
_logger.LogError(jsex,
|
||||||
|
"Could not execute timer tick for script action {ActionName} [@{LocationInfo}]", _actionName,
|
||||||
|
jsex.Location);
|
||||||
|
ReleaseThreads();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Could not execute timer tick for script action {ActionName}", _actionName);
|
||||||
|
_onRunningTick.Set();
|
||||||
|
ReleaseThreads();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SetDependency(SemaphoreSlim dependentSemaphore)
|
||||||
|
{
|
||||||
|
_onDependentAction = dependentSemaphore;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsRunning { get; private set; }
|
||||||
|
}
|
@ -31,6 +31,7 @@ namespace IW4MAdmin.Application.RConParsers
|
|||||||
public string NoticeLineSeparator { get; set; } = Environment.NewLine;
|
public string NoticeLineSeparator { get; set; } = Environment.NewLine;
|
||||||
public int? DefaultRConPort { get; set; }
|
public int? DefaultRConPort { get; set; }
|
||||||
public string DefaultInstallationDirectoryHint { get; set; }
|
public string DefaultInstallationDirectoryHint { get; set; }
|
||||||
|
public short FloodProtectInterval { get; set; } = 750;
|
||||||
|
|
||||||
public ColorCodeMapping ColorCodeMapping { get; set; } = new ColorCodeMapping
|
public ColorCodeMapping ColorCodeMapping { get; set; } = new ColorCodeMapping
|
||||||
{
|
{
|
||||||
|
@ -1,53 +0,0 @@
|
|||||||
#include common_scripts\utility;
|
|
||||||
#include maps\mp\_utility;
|
|
||||||
#include maps\mp\gametypes\_hud_util;
|
|
||||||
#include maps\mp\gametypes\_playerlogic;
|
|
||||||
|
|
||||||
init()
|
|
||||||
{
|
|
||||||
SetDvarIfUninitialized( "sv_iw4madmin_command", "" );
|
|
||||||
level thread WaitForCommand();
|
|
||||||
}
|
|
||||||
|
|
||||||
WaitForCommand()
|
|
||||||
{
|
|
||||||
level endon( "game_ended" );
|
|
||||||
|
|
||||||
for(;;)
|
|
||||||
{
|
|
||||||
commandInfo = strtok( getDvar("sv_iw4madmin_command"), ";" );
|
|
||||||
command = commandInfo[0];
|
|
||||||
|
|
||||||
switch( command )
|
|
||||||
{
|
|
||||||
case "alert":
|
|
||||||
//clientId alertType sound message
|
|
||||||
SendAlert( commandInfo[1], commandInfo[2], commandInfo[3], commandInfo[4] );
|
|
||||||
break;
|
|
||||||
case "killplayer":
|
|
||||||
// clientId
|
|
||||||
KillPlayer( commandInfo[1], commandInfo[2] );
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
setDvar( "sv_iw4madmin_command", "" );
|
|
||||||
wait( 1 );
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
SendAlert( clientId, alertType, sound, message )
|
|
||||||
{
|
|
||||||
client = getPlayerFromClientNum( int( clientId ) );
|
|
||||||
client thread playLeaderDialogOnPlayer( sound, client.team );
|
|
||||||
client playLocalSound( sound );
|
|
||||||
client iPrintLnBold( "^1" + alertType + ": ^3" + message );
|
|
||||||
}
|
|
||||||
|
|
||||||
KillPlayer( targetId, originId)
|
|
||||||
{
|
|
||||||
target = getPlayerFromClientNum( int( targetId ) );
|
|
||||||
target suicide();
|
|
||||||
origin = getPlayerFromClientNum( int( originId ) );
|
|
||||||
|
|
||||||
iPrintLnBold("^1" + origin.name + " ^7killed ^5" + target.name);
|
|
||||||
}
|
|
549
GameFiles/IW4x/userraw/scripts/_integration.gsc
Normal file
549
GameFiles/IW4x/userraw/scripts/_integration.gsc
Normal file
@ -0,0 +1,549 @@
|
|||||||
|
#include common_scripts\utility;
|
||||||
|
#include maps\mp\_utility;
|
||||||
|
#include maps\mp\gametypes\_hud_util;
|
||||||
|
#include maps\mp\gametypes\_playerlogic;
|
||||||
|
|
||||||
|
init()
|
||||||
|
{
|
||||||
|
// setup default vars
|
||||||
|
level.eventBus = spawnstruct();
|
||||||
|
level.eventBus.inVar = "sv_iw4madmin_in";
|
||||||
|
level.eventBus.outVar = "sv_iw4madmin_out";
|
||||||
|
level.eventBus.failKey = "fail";
|
||||||
|
level.eventBus.timeoutKey = "timeout";
|
||||||
|
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, "" );
|
||||||
|
SetDvarIfUninitialized( level.eventBus.outVar, "" );
|
||||||
|
SetDvarIfUninitialized( "sv_iw4madmin_integration_enabled", 1 );
|
||||||
|
SetDvarIfUninitialized( "sv_iw4madmin_integration_debug", 0 );
|
||||||
|
|
||||||
|
// 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.setClientDataCompleted] = ::OnSetClientDataCompleted;
|
||||||
|
|
||||||
|
if ( GetDvarInt( "sv_iw4madmin_integration_enabled" ) != 1 )
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// start long running tasks
|
||||||
|
level thread MonitorClientEvents();
|
||||||
|
level thread MonitorBus();
|
||||||
|
level thread OnPlayerConnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////
|
||||||
|
// Client Methods
|
||||||
|
//////////////////////////////////
|
||||||
|
|
||||||
|
OnPlayerConnect()
|
||||||
|
{
|
||||||
|
level endon ( "disconnect" );
|
||||||
|
|
||||||
|
for ( ;; )
|
||||||
|
{
|
||||||
|
level waittill( "connected", player );
|
||||||
|
|
||||||
|
level.iw4adminIntegrationDebug = GetDvarInt( "sv_iw4madmin_integration_debug" );
|
||||||
|
|
||||||
|
if ( !isDefined( player.pers[level.clientDataKey] ) )
|
||||||
|
{
|
||||||
|
player.pers[level.clientDataKey] = spawnstruct();
|
||||||
|
}
|
||||||
|
|
||||||
|
player thread OnPlayerSpawned();
|
||||||
|
player thread PlayerTrackingOnInterval();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
OnPlayerSpawned()
|
||||||
|
{
|
||||||
|
self endon( "disconnect" );
|
||||||
|
|
||||||
|
for ( ;; )
|
||||||
|
{
|
||||||
|
self waittill( "spawned_player" );
|
||||||
|
self PlayerConnectEvents();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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" || 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 );
|
||||||
|
}
|
||||||
|
|
||||||
|
PlayerConnectEvents()
|
||||||
|
{
|
||||||
|
self endon( "disconnect" );
|
||||||
|
|
||||||
|
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" )
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self RequestClientBasicData();
|
||||||
|
// example of requesting meta from IW4MAdmin
|
||||||
|
// self RequestClientMeta( "LastServerPlayed" );
|
||||||
|
}
|
||||||
|
|
||||||
|
PlayerTrackingOnInterval()
|
||||||
|
{
|
||||||
|
self endon( "disconnect" );
|
||||||
|
|
||||||
|
for ( ;; )
|
||||||
|
{
|
||||||
|
wait ( 120 );
|
||||||
|
if ( IsAlive( self ) )
|
||||||
|
{
|
||||||
|
self SaveTrackingMetrics();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MonitorClientEvents()
|
||||||
|
{
|
||||||
|
level endon( "disconnect" );
|
||||||
|
self endon( "disconnect" );
|
||||||
|
|
||||||
|
for ( ;; )
|
||||||
|
{
|
||||||
|
level waittill( level.eventTypes.localClientEvent, client );
|
||||||
|
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
self IPrintLn( "Processing Event " + client.event.type + "-" + client.event.subtype );
|
||||||
|
}
|
||||||
|
|
||||||
|
eventHandler = level.eventCallbacks[client.event.type];
|
||||||
|
|
||||||
|
if ( isDefined( eventHandler ) )
|
||||||
|
{
|
||||||
|
client [[eventHandler]]( client.event );
|
||||||
|
}
|
||||||
|
|
||||||
|
client.eventData = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////
|
||||||
|
// Helper Methods
|
||||||
|
//////////////////////////////////
|
||||||
|
|
||||||
|
RequestClientMeta( metaKey )
|
||||||
|
{
|
||||||
|
getClientMetaEvent = BuildEventRequest( true, level.eventTypes.clientDataRequested, "Meta", self, metaKey );
|
||||||
|
level thread QueueEvent( getClientMetaEvent, level.eventTypes.clientDataRequested, self );
|
||||||
|
}
|
||||||
|
|
||||||
|
RequestClientBasicData()
|
||||||
|
{
|
||||||
|
getClientDataEvent = BuildEventRequest( true, level.eventTypes.clientDataRequested, "None", self, "" );
|
||||||
|
level thread QueueEvent( getClientDataEvent, level.eventTypes.clientDataRequested, self );
|
||||||
|
}
|
||||||
|
|
||||||
|
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 ) )
|
||||||
|
{
|
||||||
|
data = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( !isDefined( eventSubtype ) )
|
||||||
|
{
|
||||||
|
eventSubtype = "None";
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( IsPlayer( entOrId ) )
|
||||||
|
{
|
||||||
|
entOrId = entOrId getEntityNumber();
|
||||||
|
}
|
||||||
|
|
||||||
|
request = "0";
|
||||||
|
|
||||||
|
if ( responseExpected )
|
||||||
|
{
|
||||||
|
request = "1";
|
||||||
|
}
|
||||||
|
|
||||||
|
request = request + ";" + eventType + ";" + eventSubtype + ";" + entOrId + ";" + data;
|
||||||
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
MonitorBus()
|
||||||
|
{
|
||||||
|
level endon( "game_ended" );
|
||||||
|
|
||||||
|
for( ;; )
|
||||||
|
{
|
||||||
|
wait ( 0.1 );
|
||||||
|
|
||||||
|
// check to see if IW4MAdmin is ready to receive more data
|
||||||
|
if ( getDvar( level.eventBus.inVar ) == "" )
|
||||||
|
{
|
||||||
|
level notify( "bus_ready" );
|
||||||
|
}
|
||||||
|
|
||||||
|
eventString = getDvar( level.eventBus.outVar );
|
||||||
|
|
||||||
|
if ( eventString == "" )
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
IPrintLn( "-> " + eventString );
|
||||||
|
}
|
||||||
|
|
||||||
|
NotifyClientEvent( strtok( eventString, ";" ) );
|
||||||
|
|
||||||
|
SetDvar( level.eventBus.outVar, "" );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
QueueEvent( request, eventType, notifyEntity )
|
||||||
|
{
|
||||||
|
level endon( "disconnect" );
|
||||||
|
|
||||||
|
start = GetTime();
|
||||||
|
maxWait = level.eventBus.timeout * 1000; // 30 seconds
|
||||||
|
timedOut = "";
|
||||||
|
|
||||||
|
while ( GetDvar( level.eventBus.inVar ) != "" && ( GetTime() - start ) < maxWait )
|
||||||
|
{
|
||||||
|
level waittill_notify_or_timeout( "bus_ready", 1 );
|
||||||
|
|
||||||
|
if ( GetDvar( level.eventBus.inVar ) != "" )
|
||||||
|
{
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
IPrintLn( "A request is already in progress..." );
|
||||||
|
}
|
||||||
|
timedOut = "set";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
timedOut = "unset";
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( timedOut == "set")
|
||||||
|
{
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
IPrintLn( "Timed out waiting for response..." );
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( IsDefined( notifyEntity) )
|
||||||
|
{
|
||||||
|
notifyEntity NotifyClientEventTimeout( eventType );
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
IPrintLn("<- " + request);
|
||||||
|
}
|
||||||
|
|
||||||
|
SetDvar( level.eventBus.inVar, request );
|
||||||
|
}
|
||||||
|
|
||||||
|
ParseDataString( data )
|
||||||
|
{
|
||||||
|
dataParts = strtok( data, "|" );
|
||||||
|
dict = [];
|
||||||
|
|
||||||
|
counter = 0;
|
||||||
|
foreach ( part in dataParts )
|
||||||
|
{
|
||||||
|
splitPart = strtok( part, "=" );
|
||||||
|
key = splitPart[0];
|
||||||
|
value = splitPart[1];
|
||||||
|
dict[key] = value;
|
||||||
|
dict[counter] = key;
|
||||||
|
counter++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return dict;
|
||||||
|
}
|
||||||
|
|
||||||
|
NotifyClientEventTimeout( eventType )
|
||||||
|
{
|
||||||
|
// todo: make this actual eventing
|
||||||
|
if ( eventType == level.eventTypes.clientDataRequested )
|
||||||
|
{
|
||||||
|
self.pers["clientData"].state = level.eventBus.timeoutKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
NotifyClientEvent( eventInfo )
|
||||||
|
{
|
||||||
|
client = getPlayerFromClientNum( int( eventInfo[3] ) );
|
||||||
|
|
||||||
|
event = spawnstruct();
|
||||||
|
event.type = eventInfo[1];
|
||||||
|
event.subtype = eventInfo[2];
|
||||||
|
event.data = eventInfo[4];
|
||||||
|
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
IPrintLn(event.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
client.event = event;
|
||||||
|
|
||||||
|
level notify( level.eventTypes.localClientEvent, client );
|
||||||
|
}
|
||||||
|
|
||||||
|
//////////////////////////////////
|
||||||
|
// Event Handlers
|
||||||
|
/////////////////////////////////
|
||||||
|
|
||||||
|
OnClientDataReceived( event )
|
||||||
|
{
|
||||||
|
event.data = ParseDataString( event.data );
|
||||||
|
clientData = self.pers[level.clientDataKey];
|
||||||
|
|
||||||
|
if ( event.subtype == "Fail" )
|
||||||
|
{
|
||||||
|
if ( level.iw4adminIntegrationDebug == 1 )
|
||||||
|
{
|
||||||
|
IPrintLn( "Received fail response" );
|
||||||
|
}
|
||||||
|
clientData.state = level.eventBus.failKey;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( event.subtype == "Meta" )
|
||||||
|
{
|
||||||
|
if ( !isDefined( clientData.meta ) )
|
||||||
|
{
|
||||||
|
clientData.meta = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
metaKey = event.data[0];
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
OnExecuteCommand( event )
|
||||||
|
{
|
||||||
|
data = ParseDataString( event.data );
|
||||||
|
switch ( event.subtype )
|
||||||
|
{
|
||||||
|
case "GiveWeapon":
|
||||||
|
self GiveWeaponImpl( data );
|
||||||
|
break;
|
||||||
|
case "TakeWeapons":
|
||||||
|
self TakeWeaponsImpl();
|
||||||
|
break;
|
||||||
|
case "SwitchTeams":
|
||||||
|
self TeamSwitchImpl();
|
||||||
|
break;
|
||||||
|
case "Hide":
|
||||||
|
self HideImpl();
|
||||||
|
break;
|
||||||
|
case "Unhide":
|
||||||
|
self UnhideImpl();
|
||||||
|
break;
|
||||||
|
case "Alert":
|
||||||
|
self AlertImpl( data );
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
/////////////////////////////////
|
||||||
|
|
||||||
|
GiveWeaponImpl( data )
|
||||||
|
{
|
||||||
|
if ( IsAlive( self ) )
|
||||||
|
{
|
||||||
|
self IPrintLnBold( "You have been given a new weapon" );
|
||||||
|
self GiveWeapon( data["weaponName"] );
|
||||||
|
self SwitchToWeapon( data["weaponName"] );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TakeWeaponsImpl()
|
||||||
|
{
|
||||||
|
if ( IsAlive( self ) )
|
||||||
|
{
|
||||||
|
self TakeAllWeapons();
|
||||||
|
self IPrintLnBold( "All your weapons have been taken" );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TeamSwitchImpl()
|
||||||
|
{
|
||||||
|
if ( self.team == "allies" )
|
||||||
|
{
|
||||||
|
self [[level.axis]]();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
self [[level.allies]]();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
HideImpl()
|
||||||
|
{
|
||||||
|
if ( IsAlive( self ) )
|
||||||
|
{
|
||||||
|
self Hide();
|
||||||
|
self IPrintLnBold( "You are now hidden" );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
UnhideImpl()
|
||||||
|
{
|
||||||
|
if ( IsAlive( self ) )
|
||||||
|
{
|
||||||
|
self Show();
|
||||||
|
self IPrintLnBold( "You are now visible" );
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
AlertImpl( data )
|
||||||
|
{
|
||||||
|
self thread maps\mp\gametypes\_hud_message::oldNotifyMessage( data["alertType"], data["message"], "compass_waypoint_target", ( 1, 0, 0 ), "ui_mp_nukebomb_timer", 7.5 );
|
||||||
|
}
|
@ -6,7 +6,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Plugins", "Plugins", "{26E8
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8C8F3945-0AEF-4949-A1F7-B18E952E50BC}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8C8F3945-0AEF-4949-A1F7-B18E952E50BC}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
GameFiles\IW4x\userraw\scripts\_commands.gsc = GameFiles\IW4x\userraw\scripts\_commands.gsc
|
|
||||||
GameFiles\IW4x\userraw\scripts\_customcallbacks.gsc = GameFiles\IW4x\userraw\scripts\_customcallbacks.gsc
|
GameFiles\IW4x\userraw\scripts\_customcallbacks.gsc = GameFiles\IW4x\userraw\scripts\_customcallbacks.gsc
|
||||||
DeploymentFiles\deployment-pipeline.yml = DeploymentFiles\deployment-pipeline.yml
|
DeploymentFiles\deployment-pipeline.yml = DeploymentFiles\deployment-pipeline.yml
|
||||||
DeploymentFiles\PostPublish.ps1 = DeploymentFiles\PostPublish.ps1
|
DeploymentFiles\PostPublish.ps1 = DeploymentFiles\PostPublish.ps1
|
||||||
@ -14,6 +13,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
|
|||||||
version.txt = version.txt
|
version.txt = version.txt
|
||||||
DeploymentFiles\UpdateIW4MAdmin.ps1 = DeploymentFiles\UpdateIW4MAdmin.ps1
|
DeploymentFiles\UpdateIW4MAdmin.ps1 = DeploymentFiles\UpdateIW4MAdmin.ps1
|
||||||
DeploymentFiles\UpdateIW4MAdmin.sh = DeploymentFiles\UpdateIW4MAdmin.sh
|
DeploymentFiles\UpdateIW4MAdmin.sh = DeploymentFiles\UpdateIW4MAdmin.sh
|
||||||
|
GameFiles\IW4x\userraw\scripts\_integration.gsc = GameFiles\IW4x\userraw\scripts\_integration.gsc
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharedLibraryCore", "SharedLibraryCore\SharedLibraryCore.csproj", "{AA0541A2-8D51-4AD9-B0AC-3D1F5B162481}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SharedLibraryCore", "SharedLibraryCore\SharedLibraryCore.csproj", "{AA0541A2-8D51-4AD9-B0AC-3D1F5B162481}"
|
||||||
@ -30,8 +30,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProfanityDeterment", "Plugi
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Login", "Plugins\Login\Login.csproj", "{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Login", "Plugins\Login\Login.csproj", "{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}"
|
||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IW4ScriptCommands", "Plugins\IW4ScriptCommands\IW4ScriptCommands.csproj", "{6C706CE5-A206-4E46-8712-F8C48D526091}"
|
|
||||||
EndProject
|
|
||||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ScriptPlugins", "ScriptPlugins", "{3F9ACC27-26DB-49FA-BCD2-50C54A49C9FA}"
|
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ScriptPlugins", "ScriptPlugins", "{3F9ACC27-26DB-49FA-BCD2-50C54A49C9FA}"
|
||||||
ProjectSection(SolutionItems) = preProject
|
ProjectSection(SolutionItems) = preProject
|
||||||
Plugins\ScriptPlugins\ActionOnReport.js = Plugins\ScriptPlugins\ActionOnReport.js
|
Plugins\ScriptPlugins\ActionOnReport.js = Plugins\ScriptPlugins\ActionOnReport.js
|
||||||
@ -52,6 +50,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ScriptPlugins", "ScriptPlug
|
|||||||
Plugins\ScriptPlugins\ParserCSGO.js = Plugins\ScriptPlugins\ParserCSGO.js
|
Plugins\ScriptPlugins\ParserCSGO.js = Plugins\ScriptPlugins\ParserCSGO.js
|
||||||
Plugins\ScriptPlugins\ParserCSGOSM.js = Plugins\ScriptPlugins\ParserCSGOSM.js
|
Plugins\ScriptPlugins\ParserCSGOSM.js = Plugins\ScriptPlugins\ParserCSGOSM.js
|
||||||
Plugins\ScriptPlugins\ParserPlutoniumT4COZM.js = Plugins\ScriptPlugins\ParserPlutoniumT4COZM.js
|
Plugins\ScriptPlugins\ParserPlutoniumT4COZM.js = Plugins\ScriptPlugins\ParserPlutoniumT4COZM.js
|
||||||
|
Plugins\ScriptPlugins\GameInterface.js = Plugins\ScriptPlugins\GameInterface.js
|
||||||
EndProjectSection
|
EndProjectSection
|
||||||
EndProject
|
EndProject
|
||||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomessageFeed", "Plugins\AutomessageFeed\AutomessageFeed.csproj", "{F5815359-CFC7-44B4-9A3B-C04BACAD5836}"
|
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomessageFeed", "Plugins\AutomessageFeed\AutomessageFeed.csproj", "{F5815359-CFC7-44B4-9A3B-C04BACAD5836}"
|
||||||
@ -252,30 +251,6 @@ Global
|
|||||||
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}.Release|x64.Build.0 = Release|Any CPU
|
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}.Release|x86.ActiveCfg = Release|Any CPU
|
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}.Release|x86.Build.0 = Release|Any CPU
|
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}.Release|x86.Build.0 = Release|Any CPU
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|x64.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Debug|x86.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|Any CPU.ActiveCfg = Prerelease|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|Any CPU.Build.0 = Prerelease|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|Mixed Platforms.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|x64.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|x64.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|x86.ActiveCfg = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Prerelease|x86.Build.0 = Debug|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|x64.ActiveCfg = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|x64.Build.0 = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|x86.ActiveCfg = Release|Any CPU
|
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091}.Release|x86.Build.0 = Release|Any CPU
|
|
||||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||||
@ -405,7 +380,6 @@ Global
|
|||||||
{179140D3-97AA-4CB4-8BF6-A0C73CA75701} = {26E8B310-269E-46D4-A612-24601F16065F}
|
{179140D3-97AA-4CB4-8BF6-A0C73CA75701} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||||
{958FF7EC-0226-4E85-A85B-B84EC768197D} = {26E8B310-269E-46D4-A612-24601F16065F}
|
{958FF7EC-0226-4E85-A85B-B84EC768197D} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||||
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1} = {26E8B310-269E-46D4-A612-24601F16065F}
|
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||||
{6C706CE5-A206-4E46-8712-F8C48D526091} = {26E8B310-269E-46D4-A612-24601F16065F}
|
|
||||||
{3F9ACC27-26DB-49FA-BCD2-50C54A49C9FA} = {26E8B310-269E-46D4-A612-24601F16065F}
|
{3F9ACC27-26DB-49FA-BCD2-50C54A49C9FA} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836} = {26E8B310-269E-46D4-A612-24601F16065F}
|
{F5815359-CFC7-44B4-9A3B-C04BACAD5836} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||||
{00A1FED2-2254-4AF7-A5DB-2357FA7C88CD} = {26E8B310-269E-46D4-A612-24601F16065F}
|
{00A1FED2-2254-4AF7-A5DB-2357FA7C88CD} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||||
|
@ -64,9 +64,9 @@ namespace Integrations.Cod
|
|||||||
|
|
||||||
var timeSinceLastQuery = (DateTime.Now - connectionState.LastQuery).TotalMilliseconds;
|
var timeSinceLastQuery = (DateTime.Now - connectionState.LastQuery).TotalMilliseconds;
|
||||||
|
|
||||||
if (timeSinceLastQuery < StaticHelpers.FloodProtectionInterval)
|
if (timeSinceLastQuery < config.FloodProtectInterval)
|
||||||
{
|
{
|
||||||
await Task.Delay(StaticHelpers.FloodProtectionInterval - (int)timeSinceLastQuery);
|
await Task.Delay(config.FloodProtectInterval - (int)timeSinceLastQuery);
|
||||||
}
|
}
|
||||||
|
|
||||||
connectionState.LastQuery = DateTime.Now;
|
connectionState.LastQuery = DateTime.Now;
|
||||||
@ -150,9 +150,9 @@ namespace Integrations.Cod
|
|||||||
})
|
})
|
||||||
{
|
{
|
||||||
connectionState.SendEventArgs.UserToken = socket;
|
connectionState.SendEventArgs.UserToken = socket;
|
||||||
connectionState.OnSentData.Reset();
|
|
||||||
connectionState.OnReceivedData.Reset();
|
|
||||||
connectionState.ConnectionAttempts++;
|
connectionState.ConnectionAttempts++;
|
||||||
|
await connectionState.OnSentData.WaitAsync();
|
||||||
|
await connectionState.OnReceivedData.WaitAsync();
|
||||||
connectionState.BytesReadPerSegment.Clear();
|
connectionState.BytesReadPerSegment.Clear();
|
||||||
bool exceptionCaught = false;
|
bool exceptionCaught = false;
|
||||||
|
|
||||||
@ -199,6 +199,16 @@ namespace Integrations.Cod
|
|||||||
{
|
{
|
||||||
connectionState.OnComplete.Release(1);
|
connectionState.OnComplete.Release(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (connectionState.OnSentData.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
connectionState.OnSentData.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (connectionState.OnReceivedData.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
connectionState.OnReceivedData.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -328,7 +338,8 @@ namespace Integrations.Cod
|
|||||||
{
|
{
|
||||||
// the send has not been completed asynchronously
|
// the send has not been completed asynchronously
|
||||||
// this really shouldn't ever happen because it's UDP
|
// this really shouldn't ever happen because it's UDP
|
||||||
if (!await Task.Run(() => connectionState.OnSentData.Wait(StaticHelpers.SocketTimeout(1))))
|
|
||||||
|
if(!await connectionState.OnSentData.WaitAsync(StaticHelpers.SocketTimeout(1)))
|
||||||
{
|
{
|
||||||
using(LogContext.PushProperty("Server", Endpoint.ToString()))
|
using(LogContext.PushProperty("Server", Endpoint.ToString()))
|
||||||
{
|
{
|
||||||
@ -342,7 +353,7 @@ namespace Integrations.Cod
|
|||||||
|
|
||||||
if (!waitForResponse)
|
if (!waitForResponse)
|
||||||
{
|
{
|
||||||
return new byte[0][];
|
return Array.Empty<byte[]>();
|
||||||
}
|
}
|
||||||
|
|
||||||
connectionState.ReceiveEventArgs.SetBuffer(connectionState.ReceiveBuffer);
|
connectionState.ReceiveEventArgs.SetBuffer(connectionState.ReceiveBuffer);
|
||||||
@ -353,12 +364,12 @@ namespace Integrations.Cod
|
|||||||
if (receiveDataPending)
|
if (receiveDataPending)
|
||||||
{
|
{
|
||||||
_log.LogDebug("Waiting to asynchronously receive data on attempt #{connectionAttempts}", connectionState.ConnectionAttempts);
|
_log.LogDebug("Waiting to asynchronously receive data on attempt #{connectionAttempts}", connectionState.ConnectionAttempts);
|
||||||
if (!await Task.Run(() => connectionState.OnReceivedData.Wait(
|
if (!await connectionState.OnReceivedData.WaitAsync(
|
||||||
new[]
|
new[]
|
||||||
{
|
{
|
||||||
StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts),
|
StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts),
|
||||||
overrideTimeout
|
overrideTimeout
|
||||||
}.Max())))
|
}.Max()))
|
||||||
{
|
{
|
||||||
if (connectionState.ConnectionAttempts > 1) // this reduces some spam for unstable connections
|
if (connectionState.ConnectionAttempts > 1) // this reduces some spam for unstable connections
|
||||||
{
|
{
|
||||||
@ -407,12 +418,24 @@ namespace Integrations.Cod
|
|||||||
if (e.BytesTransferred == 0)
|
if (e.BytesTransferred == 0)
|
||||||
{
|
{
|
||||||
_log.LogDebug("No bytes were transmitted so the connection was probably closed");
|
_log.LogDebug("No bytes were transmitted so the connection was probably closed");
|
||||||
ActiveQueries[this.Endpoint].OnReceivedData.Set();
|
|
||||||
|
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||||
|
if (semaphore.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!(sender is Socket sock))
|
if (sender is not Socket sock)
|
||||||
{
|
{
|
||||||
|
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||||
|
if (semaphore.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -427,16 +450,19 @@ namespace Integrations.Cod
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var totalBytesTransferred = e.BytesTransferred;
|
var totalBytesTransferred = e.BytesTransferred;
|
||||||
_log.LogDebug("{total} total bytes transferred with {available} bytes remaining", totalBytesTransferred, sock.Available);
|
_log.LogDebug("{total} total bytes transferred with {available} bytes remaining", totalBytesTransferred,
|
||||||
|
sock.Available);
|
||||||
// we still have available data so the payload was segmented
|
// we still have available data so the payload was segmented
|
||||||
while (sock.Available > 0)
|
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;
|
var bufferSpaceAvailable = sock.Available + totalBytesTransferred - state.ReceiveBuffer.Length;
|
||||||
if (bufferSpaceAvailable >= 0 )
|
if (bufferSpaceAvailable >= 0)
|
||||||
{
|
{
|
||||||
_log.LogWarning("Not enough buffer space to store incoming data {bytesNeeded} additional bytes required", bufferSpaceAvailable);
|
_log.LogWarning(
|
||||||
|
"Not enough buffer space to store incoming data {bytesNeeded} additional bytes required",
|
||||||
|
bufferSpaceAvailable);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -448,26 +474,38 @@ namespace Integrations.Cod
|
|||||||
continue;
|
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);
|
||||||
// we need to increment this here because the callback isn't executed if there's no pending IO
|
// we need to increment this here because the callback isn't executed if there's no pending IO
|
||||||
state.BytesReadPerSegment.Add(state.ReceiveEventArgs.BytesTransferred);
|
state.BytesReadPerSegment.Add(state.ReceiveEventArgs.BytesTransferred);
|
||||||
totalBytesTransferred += state.ReceiveEventArgs.BytesTransferred;
|
totalBytesTransferred += state.ReceiveEventArgs.BytesTransferred;
|
||||||
}
|
}
|
||||||
|
|
||||||
ActiveQueries[this.Endpoint].OnReceivedData.Set();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
catch (ObjectDisposedException)
|
catch (ObjectDisposedException)
|
||||||
{
|
{
|
||||||
_log.LogDebug("Socket was disposed while receiving data");
|
_log.LogDebug("Socket was disposed while receiving data");
|
||||||
ActiveQueries[this.Endpoint].OnReceivedData.Set();
|
}
|
||||||
|
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||||
|
if (semaphore.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnDataSent(object sender, SocketAsyncEventArgs e)
|
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);
|
||||||
ActiveQueries[this.Endpoint].OnSentData.Set();
|
|
||||||
|
var semaphore = ActiveQueries[this.Endpoint].OnSentData;
|
||||||
|
if (semaphore.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
semaphore.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -21,8 +21,9 @@ namespace Integrations.Cod
|
|||||||
private const int BufferSize = 16384;
|
private const int BufferSize = 16384;
|
||||||
public readonly byte[] ReceiveBuffer = new byte[BufferSize];
|
public readonly byte[] ReceiveBuffer = new byte[BufferSize];
|
||||||
public readonly SemaphoreSlim OnComplete = new SemaphoreSlim(1, 1);
|
public readonly SemaphoreSlim OnComplete = new SemaphoreSlim(1, 1);
|
||||||
public readonly ManualResetEventSlim OnSentData = new ManualResetEventSlim(false);
|
public readonly SemaphoreSlim OnSentData = new(1, 1);
|
||||||
public readonly ManualResetEventSlim OnReceivedData = new ManualResetEventSlim(false);
|
public readonly SemaphoreSlim OnReceivedData = new (1, 1);
|
||||||
|
|
||||||
public List<int> BytesReadPerSegment { get; set; } = new List<int>();
|
public List<int> BytesReadPerSegment { get; set; } = new List<int>();
|
||||||
public SocketAsyncEventArgs SendEventArgs { get; set; } = new SocketAsyncEventArgs();
|
public SocketAsyncEventArgs SendEventArgs { get; set; } = new SocketAsyncEventArgs();
|
||||||
public SocketAsyncEventArgs ReceiveEventArgs { get; set; } = new SocketAsyncEventArgs();
|
public SocketAsyncEventArgs ReceiveEventArgs { get; set; } = new SocketAsyncEventArgs();
|
||||||
|
@ -1,44 +0,0 @@
|
|||||||
using SharedLibraryCore;
|
|
||||||
using SharedLibraryCore.Commands;
|
|
||||||
using SharedLibraryCore.Configuration;
|
|
||||||
using SharedLibraryCore.Database.Models;
|
|
||||||
using SharedLibraryCore.Interfaces;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace IW4ScriptCommands.Commands
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Example script command
|
|
||||||
/// </summary>
|
|
||||||
public class KillPlayerCommand : Command
|
|
||||||
{
|
|
||||||
public KillPlayerCommand(CommandConfiguration config, ITranslationLookup lookup) : base(config, lookup)
|
|
||||||
{
|
|
||||||
Name = "killplayer";
|
|
||||||
Description = "kill a player";
|
|
||||||
Alias = "kp";
|
|
||||||
Permission = EFClient.Permission.Administrator;
|
|
||||||
RequiresTarget = true;
|
|
||||||
Arguments = new[]
|
|
||||||
{
|
|
||||||
new CommandArgument()
|
|
||||||
{
|
|
||||||
Name = "player",
|
|
||||||
Required = true
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
public override async Task ExecuteAsync(GameEvent E)
|
|
||||||
{
|
|
||||||
var cmd = new ScriptCommand()
|
|
||||||
{
|
|
||||||
CommandName = "killplayer",
|
|
||||||
ClientNumber = E.Target.ClientNumber,
|
|
||||||
CommandArguments = new[] { E.Origin.ClientNumber.ToString() }
|
|
||||||
};
|
|
||||||
|
|
||||||
await cmd.Execute(E.Owner);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,44 +0,0 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using SharedLibraryCore;
|
|
||||||
using SharedLibraryCore.Interfaces;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace WebfrontCore.Controllers.API
|
|
||||||
{
|
|
||||||
[Route("api/gsc/[action]")]
|
|
||||||
public class GscApiController : BaseController
|
|
||||||
{
|
|
||||||
public GscApiController(IManager manager) : base(manager)
|
|
||||||
{
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// grabs basic info about the client from IW4MAdmin
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="networkId"></param>
|
|
||||||
/// <returns></returns>
|
|
||||||
[HttpGet("{networkId}")]
|
|
||||||
public IActionResult ClientInfo(string networkId)
|
|
||||||
{
|
|
||||||
long decimalNetworkId = networkId.ConvertGuidToLong(System.Globalization.NumberStyles.HexNumber);
|
|
||||||
var clientInfo = Manager.GetActiveClients()
|
|
||||||
.FirstOrDefault(c => c.NetworkId == decimalNetworkId);
|
|
||||||
|
|
||||||
if (clientInfo != null)
|
|
||||||
{
|
|
||||||
var sb = new StringBuilder();
|
|
||||||
sb.AppendLine($"admin={clientInfo.IsPrivileged()}");
|
|
||||||
sb.AppendLine($"level={(int)clientInfo.Level}");
|
|
||||||
sb.AppendLine($"levelstring={clientInfo.Level.ToLocalizedLevelName()}");
|
|
||||||
sb.AppendLine($"connections={clientInfo.Connections}");
|
|
||||||
sb.AppendLine($"authenticated={clientInfo.GetAdditionalProperty<bool>("IsLoggedIn") == true}");
|
|
||||||
|
|
||||||
return Content(sb.ToString());
|
|
||||||
}
|
|
||||||
|
|
||||||
return Content("");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,20 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<OutputType>Library</OutputType>
|
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
|
||||||
<ApplicationIcon />
|
|
||||||
<StartupObject />
|
|
||||||
<Configurations>Debug;Release;Prerelease</Configurations>
|
|
||||||
<LangVersion>Latest</LangVersion>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2022.1.28.1" PrivateAssets="All" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
|
||||||
<Exec Command="dotnet publish $(ProjectPath) -c $(ConfigurationName) -o $(ProjectDir)..\..\Build\Plugins --no-build --no-restore --no-dependencies" />
|
|
||||||
</Target>
|
|
||||||
|
|
||||||
</Project>
|
|
@ -1,46 +0,0 @@
|
|||||||
using SharedLibraryCore;
|
|
||||||
using SharedLibraryCore.Interfaces;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace IW4ScriptCommands
|
|
||||||
{
|
|
||||||
public class Plugin : IPlugin
|
|
||||||
{
|
|
||||||
public string Name => "IW4 Script Commands";
|
|
||||||
|
|
||||||
public float Version => 1.0f;
|
|
||||||
|
|
||||||
public string Author => "RaidMax";
|
|
||||||
|
|
||||||
public async Task OnEventAsync(GameEvent E, Server S)
|
|
||||||
{
|
|
||||||
if (E.Type == GameEvent.EventType.Start)
|
|
||||||
{
|
|
||||||
await S.SetDvarAsync("sv_iw4madmin_serverid", S.EndPoint);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (E.Type == GameEvent.EventType.Warn)
|
|
||||||
{
|
|
||||||
var cmd = new ScriptCommand()
|
|
||||||
{
|
|
||||||
ClientNumber = E.Target.ClientNumber,
|
|
||||||
CommandName = "alert",
|
|
||||||
CommandArguments = new[]
|
|
||||||
{
|
|
||||||
"Warning",
|
|
||||||
"ui_mp_nukebomb_timer",
|
|
||||||
E.Data
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// notifies the player ingame of the warning
|
|
||||||
await cmd.Execute(S);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public Task OnLoadAsync(IManager manager) => Task.CompletedTask;
|
|
||||||
|
|
||||||
public Task OnTickAsync(Server S) => Task.CompletedTask;
|
|
||||||
|
|
||||||
public Task OnUnloadAsync() => Task.CompletedTask;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
using SharedLibraryCore;
|
|
||||||
using System.Linq;
|
|
||||||
using System.Threading.Tasks;
|
|
||||||
|
|
||||||
namespace IW4ScriptCommands
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Contains basic properties for command information read by gsc
|
|
||||||
/// </summary>
|
|
||||||
class ScriptCommand
|
|
||||||
{
|
|
||||||
/// <summary>
|
|
||||||
/// Name of the command to execute
|
|
||||||
/// </summary>
|
|
||||||
public string CommandName { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Target client number
|
|
||||||
/// </summary>
|
|
||||||
public int ClientNumber { get; set; }
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Arguments for the script function itself
|
|
||||||
/// </summary>
|
|
||||||
public string[] CommandArguments { get; set; } = new string[0];
|
|
||||||
|
|
||||||
public override string ToString() => string.Join(";", new[] { CommandName, ClientNumber.ToString() }.Concat(CommandArguments).Select(_arg => _arg.Replace(";", "")));
|
|
||||||
|
|
||||||
/// <summary>
|
|
||||||
/// Executes the command
|
|
||||||
/// </summary>
|
|
||||||
/// <param name="server">server to execute the command on</param>
|
|
||||||
/// <returns></returns>
|
|
||||||
public async Task Execute(Server server) => await server.SetDvarAsync("sv_iw4madmin_command", ToString());
|
|
||||||
}
|
|
||||||
}
|
|
434
Plugins/ScriptPlugins/GameInterface.js
Normal file
434
Plugins/ScriptPlugins/GameInterface.js
Normal file
@ -0,0 +1,434 @@
|
|||||||
|
const eventTypes = {
|
||||||
|
1: 'start', // a server started being monitored
|
||||||
|
6: 'disconnect', // a client detected a leaving the game
|
||||||
|
9: 'preconnect', // client detected as joining via log or status
|
||||||
|
101: 'warn' // client was warned
|
||||||
|
};
|
||||||
|
|
||||||
|
const servers = {};
|
||||||
|
const inDvar = 'sv_iw4madmin_in';
|
||||||
|
const outDvar = 'sv_iw4madmin_out';
|
||||||
|
const pollRate = 750;
|
||||||
|
let logger = {};
|
||||||
|
|
||||||
|
let plugin = {
|
||||||
|
author: 'RaidMax',
|
||||||
|
version: 1.0,
|
||||||
|
name: 'Game Interface',
|
||||||
|
|
||||||
|
onEventAsync: (gameEvent, server) => {
|
||||||
|
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);
|
||||||
|
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'preconnect':
|
||||||
|
// when the plugin is reloaded after the servers are started
|
||||||
|
if (servers[server.EndPoint] === undefined || servers[server.EndPoint] == null) {
|
||||||
|
const enabled = initialize(server);
|
||||||
|
|
||||||
|
if (!enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const timer = servers[server.EndPoint].timer;
|
||||||
|
if (!timer.IsRunning) {
|
||||||
|
timer.Start(0, pollRate);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'warn':
|
||||||
|
const warningTitle = _localization.LocalizationIndex['GLOBAL_WARNING'];
|
||||||
|
sendScriptCommand(server, 'Alert', gameEvent.Target, {
|
||||||
|
alertType: warningTitle + '!',
|
||||||
|
message: gameEvent.Data
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
onLoadAsync: manager => {
|
||||||
|
logger = _serviceResolver.ResolveService('ILogger');
|
||||||
|
logger.WriteInfo('Game Interface Startup');
|
||||||
|
},
|
||||||
|
|
||||||
|
onUnloadAsync: () => {
|
||||||
|
for (let i = 0; i < servers.length; i++) {
|
||||||
|
if (servers[i].enabled) {
|
||||||
|
servers[i].timer.Stop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
onTickAsync: server => {
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let commands = [{
|
||||||
|
// required
|
||||||
|
name: 'giveweapon',
|
||||||
|
// required
|
||||||
|
description: 'gives specified weapon',
|
||||||
|
// required
|
||||||
|
alias: 'gw',
|
||||||
|
// required
|
||||||
|
permission: 'SeniorAdmin',
|
||||||
|
// optional (defaults to false)
|
||||||
|
targetRequired: false,
|
||||||
|
// optional
|
||||||
|
arguments: [{
|
||||||
|
name: 'weapon name',
|
||||||
|
required: true
|
||||||
|
}],
|
||||||
|
supportedGames: ['IW4'],
|
||||||
|
// required
|
||||||
|
execute: (gameEvent) => {
|
||||||
|
sendScriptCommand(gameEvent.Owner, 'GiveWeapon', gameEvent.Origin, {weaponName: gameEvent.Data});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// required
|
||||||
|
name: 'takeweapons',
|
||||||
|
// required
|
||||||
|
description: 'take all weapons from specifies player',
|
||||||
|
// required
|
||||||
|
alias: 'tw',
|
||||||
|
// required
|
||||||
|
permission: 'SeniorAdmin',
|
||||||
|
// optional (defaults to false)
|
||||||
|
targetRequired: true,
|
||||||
|
// optional
|
||||||
|
arguments: [],
|
||||||
|
supportedGames: ['IW4'],
|
||||||
|
// required
|
||||||
|
execute: (gameEvent) => {
|
||||||
|
sendScriptCommand(gameEvent.Owner, 'TakeWeapons', gameEvent.Target, undefined);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// required
|
||||||
|
name: 'switchteam',
|
||||||
|
// required
|
||||||
|
description: 'switches specified player to the opposite team',
|
||||||
|
// required
|
||||||
|
alias: 'st',
|
||||||
|
// required
|
||||||
|
permission: 'Administrator',
|
||||||
|
// optional (defaults to false)
|
||||||
|
targetRequired: true,
|
||||||
|
// optional
|
||||||
|
arguments: [{
|
||||||
|
name: 'player',
|
||||||
|
required: true
|
||||||
|
}],
|
||||||
|
supportedGames: ['IW4'],
|
||||||
|
// required
|
||||||
|
execute: (gameEvent) => {
|
||||||
|
sendScriptCommand(gameEvent.Owner, 'SwitchTeams', gameEvent.Target, undefined);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// required
|
||||||
|
name: 'hide',
|
||||||
|
// required
|
||||||
|
description: 'hide yourself',
|
||||||
|
// required
|
||||||
|
alias: 'hi',
|
||||||
|
// required
|
||||||
|
permission: 'SeniorAdmin',
|
||||||
|
// optional (defaults to false)
|
||||||
|
targetRequired: false,
|
||||||
|
// optional
|
||||||
|
arguments: [],
|
||||||
|
supportedGames: ['IW4'],
|
||||||
|
// required
|
||||||
|
execute: (gameEvent) => {
|
||||||
|
sendScriptCommand(gameEvent.Owner, 'Hide', gameEvent.Origin, undefined);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// required
|
||||||
|
name: 'unhide',
|
||||||
|
// required
|
||||||
|
description: 'unhide yourself',
|
||||||
|
// required
|
||||||
|
alias: 'unh',
|
||||||
|
// required
|
||||||
|
permission: 'SeniorAdmin',
|
||||||
|
// optional (defaults to false)
|
||||||
|
targetRequired: false,
|
||||||
|
// optional
|
||||||
|
arguments: [],
|
||||||
|
supportedGames: ['IW4'],
|
||||||
|
// required
|
||||||
|
execute: (gameEvent) => {
|
||||||
|
sendScriptCommand(gameEvent.Owner, 'Unhide', gameEvent.Origin, undefined);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// required
|
||||||
|
name: 'alert',
|
||||||
|
// required
|
||||||
|
description: 'alert a player',
|
||||||
|
// required
|
||||||
|
alias: 'alr',
|
||||||
|
// required
|
||||||
|
permission: 'SeniorAdmin',
|
||||||
|
// optional (defaults to false)
|
||||||
|
targetRequired: true,
|
||||||
|
// optional
|
||||||
|
arguments: [{
|
||||||
|
name: 'player',
|
||||||
|
required: true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'message',
|
||||||
|
required: true
|
||||||
|
}],
|
||||||
|
supportedGames: ['IW4'],
|
||||||
|
// required
|
||||||
|
execute: (gameEvent) => {
|
||||||
|
sendScriptCommand(gameEvent.Owner, 'Alert', gameEvent.Target, {
|
||||||
|
alertType: 'Alert',
|
||||||
|
message: gameEvent.Data
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}];
|
||||||
|
|
||||||
|
const sendScriptCommand = (server, command, target, data) => {
|
||||||
|
const state = servers[server.EndPoint];
|
||||||
|
if (state === undefined || !state.enabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
sendEvent(server, false, 'ExecuteCommandRequested', command, target, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sendEvent = (server, responseExpected, event, subtype, client, data) => {
|
||||||
|
const logger = _serviceResolver.ResolveService('ILogger');
|
||||||
|
|
||||||
|
let pendingOut = true;
|
||||||
|
let pendingCheckCount = 0;
|
||||||
|
const start = new Date();
|
||||||
|
|
||||||
|
while (pendingOut && pendingCheckCount <= 10) {
|
||||||
|
try {
|
||||||
|
const out = server.GetServerDvar(outDvar);
|
||||||
|
pendingOut = !(out == null || out === '' || out === 'null');
|
||||||
|
} catch (error) {
|
||||||
|
logger.WriteError(`Could not check server output dvar for IO status ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pendingOut) {
|
||||||
|
logger.WriteDebug('Waiting for event bus to be cleared');
|
||||||
|
System.Threading.Tasks.Task.Delay(1000).Wait();
|
||||||
|
}
|
||||||
|
pendingCheckCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pendingOut) {
|
||||||
|
logger.WriteWarning(`Reached maximum attempts waiting for output to be available for ${server.EndPoint}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = `${responseExpected ? '1' : '0'};${event};${subtype};${client.ClientNumber};${buildDataString(data)}`;
|
||||||
|
logger.WriteDebug(`Sending output to server ${output}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
server.SetServerDvar(outDvar, output);
|
||||||
|
logger.WriteDebug(`SendEvent took ${(new Date() - start) / 1000}ms`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.WriteError(`Could not set server output dvar ${error}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const parseEvent = (input) => {
|
||||||
|
if (input === undefined) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventInfo = input.split(';');
|
||||||
|
|
||||||
|
return {
|
||||||
|
eventType: eventInfo[1],
|
||||||
|
subType: eventInfo[2],
|
||||||
|
clientNumber: eventInfo[3],
|
||||||
|
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';
|
||||||
|
} catch (error) {
|
||||||
|
logger.WriteError(`Could not get integration status of ${server.EndPoint} - ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.WriteInfo(`GSC Integration enabled = ${enabled}`);
|
||||||
|
|
||||||
|
if (!enabled) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.WriteDebug(`Setting up bus timer for ${server.EndPoint}`);
|
||||||
|
|
||||||
|
let timer = _serviceResolver.ResolveService('IScriptPluginTimerHelper');
|
||||||
|
timer.OnTick(() => pollForEvents(server), `GameEventPoller ${server.ToString()}`);
|
||||||
|
// necessary to prevent multi-threaded access to the JS context
|
||||||
|
timer.SetDependency(_lock);
|
||||||
|
|
||||||
|
servers[server.EndPoint].timer = timer;
|
||||||
|
servers[server.EndPoint].enabled = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
server.SetServerDvar(inDvar, '');
|
||||||
|
server.SetServerDvar(outDvar, '');
|
||||||
|
} catch (error) {
|
||||||
|
logger.WriteError(`Could set default values bus dvars for ${server.EndPoint} - ${error}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
const pollForEvents = server => {
|
||||||
|
const logger = _serviceResolver.ResolveService('ILogger');
|
||||||
|
|
||||||
|
let input;
|
||||||
|
try {
|
||||||
|
input = server.GetServerDvar(inDvar);
|
||||||
|
} catch (error) {
|
||||||
|
logger.WriteError(`Could not get input bus value for ${server.EndPoint} - ${error}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input === undefined || input === null || input === 'null') {
|
||||||
|
input = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.length > 0) {
|
||||||
|
const event = parseEvent(input)
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
if (client != null) {
|
||||||
|
logger.WriteDebug(`Found client ${client.Name}`);
|
||||||
|
|
||||||
|
let data = [];
|
||||||
|
|
||||||
|
if (event.subType === 'Meta') {
|
||||||
|
const metaService = _serviceResolver.ResolveService('IMetaService');
|
||||||
|
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
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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'});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
server.SetServerDvar(inDvar, '');
|
||||||
|
} catch (error) {
|
||||||
|
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 => {
|
||||||
|
if (data === undefined) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
let formattedData = '';
|
||||||
|
|
||||||
|
for (const prop in data) {
|
||||||
|
formattedData += `${prop}=${data[prop]}|`;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
@ -3,7 +3,7 @@ var eventParser;
|
|||||||
|
|
||||||
var plugin = {
|
var plugin = {
|
||||||
author: 'RaidMax',
|
author: 'RaidMax',
|
||||||
version: 0.5,
|
version: 0.6,
|
||||||
name: 'IW4x Parser',
|
name: 'IW4x Parser',
|
||||||
isParser: true,
|
isParser: true,
|
||||||
|
|
||||||
@ -22,6 +22,7 @@ var plugin = {
|
|||||||
|
|
||||||
rconParser.Configuration.DefaultRConPort = 28960;
|
rconParser.Configuration.DefaultRConPort = 28960;
|
||||||
rconParser.Configuration.DefaultInstallationDirectoryHint = 'HKEY_CURRENT_USER\\Software\\Classes\\iw4x\\shell\\open\\command';
|
rconParser.Configuration.DefaultInstallationDirectoryHint = 'HKEY_CURRENT_USER\\Software\\Classes\\iw4x\\shell\\open\\command';
|
||||||
|
rconParser.Configuration.FloodProtectInterval = 150;
|
||||||
|
|
||||||
eventParser.Configuration.GameDirectory = 'userraw';
|
eventParser.Configuration.GameDirectory = 'userraw';
|
||||||
|
|
||||||
|
@ -249,7 +249,7 @@ namespace SharedLibraryCore
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static long NextEventId;
|
private static long NextEventId;
|
||||||
private readonly ManualResetEvent _eventFinishedWaiter;
|
private readonly SemaphoreSlim _eventFinishedWaiter = new(0, 1);
|
||||||
public string Data; // Data is usually the message sent by player
|
public string Data; // Data is usually the message sent by player
|
||||||
public string Message;
|
public string Message;
|
||||||
public EFClient Origin;
|
public EFClient Origin;
|
||||||
@ -260,11 +260,15 @@ namespace SharedLibraryCore
|
|||||||
|
|
||||||
public GameEvent()
|
public GameEvent()
|
||||||
{
|
{
|
||||||
_eventFinishedWaiter = new ManualResetEvent(false);
|
|
||||||
Time = DateTime.UtcNow;
|
Time = DateTime.UtcNow;
|
||||||
Id = GetNextEventId();
|
Id = GetNextEventId();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
~GameEvent()
|
||||||
|
{
|
||||||
|
_eventFinishedWaiter.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
public EventSource Source { get; set; }
|
public EventSource Source { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@ -299,15 +303,12 @@ namespace SharedLibraryCore
|
|||||||
return Interlocked.Increment(ref NextEventId);
|
return Interlocked.Increment(ref NextEventId);
|
||||||
}
|
}
|
||||||
|
|
||||||
~GameEvent()
|
|
||||||
{
|
|
||||||
_eventFinishedWaiter.Set();
|
|
||||||
_eventFinishedWaiter.Dispose();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void Complete()
|
public void Complete()
|
||||||
{
|
{
|
||||||
_eventFinishedWaiter.Set();
|
if (_eventFinishedWaiter.CurrentCount == 0)
|
||||||
|
{
|
||||||
|
_eventFinishedWaiter.Release();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<GameEvent> WaitAsync()
|
public async Task<GameEvent> WaitAsync()
|
||||||
@ -325,7 +326,7 @@ namespace SharedLibraryCore
|
|||||||
Utilities.DefaultLogger.LogDebug("Begin wait for event {Id}", Id);
|
Utilities.DefaultLogger.LogDebug("Begin wait for event {Id}", Id);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
processed = await Task.Run(() => _eventFinishedWaiter.WaitOne(timeSpan), token);
|
processed = await _eventFinishedWaiter.WaitAsync(timeSpan, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
catch (TaskCanceledException)
|
catch (TaskCanceledException)
|
||||||
|
@ -23,7 +23,8 @@ namespace SharedLibraryCore.Interfaces
|
|||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="fileSizeDiff"></param>
|
/// <param name="fileSizeDiff"></param>
|
||||||
/// <param name="startPosition"></param>
|
/// <param name="startPosition"></param>
|
||||||
|
/// <param name="server"></param>
|
||||||
/// <returns></returns>
|
/// <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>
|
/// <returns></returns>
|
||||||
Task AddPersistentMeta(string metaKey, string metaValue, EFClient client, EFMeta linkedMeta = null);
|
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>
|
/// <summary>
|
||||||
/// adds or updates meta key and value to the database
|
/// adds or updates meta key and value to the database
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
@ -10,7 +10,7 @@ namespace SharedLibraryCore.Interfaces
|
|||||||
bool IsParser => false;
|
bool IsParser => false;
|
||||||
Task OnLoadAsync(IManager manager);
|
Task OnLoadAsync(IManager manager);
|
||||||
Task OnUnloadAsync();
|
Task OnUnloadAsync();
|
||||||
Task OnEventAsync(GameEvent E, Server S);
|
Task OnEventAsync(GameEvent gameEvent, Server server);
|
||||||
Task OnTickAsync(Server S);
|
Task OnTickAsync(Server S);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -100,5 +100,7 @@ namespace SharedLibraryCore.Interfaces
|
|||||||
string DefaultInstallationDirectoryHint { get; }
|
string DefaultInstallationDirectoryHint { get; }
|
||||||
|
|
||||||
ColorCodeMapping ColorCodeMapping { get; }
|
ColorCodeMapping ColorCodeMapping { get; }
|
||||||
|
|
||||||
|
short FloodProtectInterval { get; }
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,5 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace SharedLibraryCore.Interfaces
|
namespace SharedLibraryCore.Interfaces
|
||||||
{
|
{
|
||||||
@ -18,8 +19,10 @@ namespace SharedLibraryCore.Interfaces
|
|||||||
/// <param name="isTargetRequired">target required or not</param>
|
/// <param name="isTargetRequired">target required or not</param>
|
||||||
/// <param name="args">command arguments (name, is required)</param>
|
/// <param name="args">command arguments (name, is required)</param>
|
||||||
/// <param name="executeAction">action to peform when commmand is executed</param>
|
/// <param name="executeAction">action to peform when commmand is executed</param>
|
||||||
|
/// <param name="supportedGames"></param>
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
IManagerCommand CreateScriptCommand(string name, string alias, string description, string permission,
|
IManagerCommand CreateScriptCommand(string name, string alias, string description, string permission,
|
||||||
bool isTargetRequired, IEnumerable<(string, bool)> args, Action<GameEvent> executeAction);
|
bool isTargetRequired, IEnumerable<(string, bool)> args, Func<GameEvent, Task> executeAction,
|
||||||
|
Server.Game[] supportedGames);
|
||||||
}
|
}
|
||||||
}
|
}
|
15
SharedLibraryCore/Interfaces/IScriptPluginTimerHelper.cs
Normal file
15
SharedLibraryCore/Interfaces/IScriptPluginTimerHelper.cs
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
using System;
|
||||||
|
using System.Threading;
|
||||||
|
|
||||||
|
namespace SharedLibraryCore.Interfaces;
|
||||||
|
|
||||||
|
public interface IScriptPluginTimerHelper
|
||||||
|
{
|
||||||
|
void Start(int delay, int interval);
|
||||||
|
void Start(int interval);
|
||||||
|
void Start();
|
||||||
|
void Stop();
|
||||||
|
void OnTick(Delegate action, string actionName);
|
||||||
|
bool IsRunning { get; }
|
||||||
|
void SetDependency(SemaphoreSlim dependentSemaphore);
|
||||||
|
}
|
@ -387,5 +387,54 @@ namespace SharedLibraryCore
|
|||||||
}
|
}
|
||||||
|
|
||||||
public abstract Task<long> GetIdForServer(Server server = null);
|
public abstract Task<long> GetIdForServer(Server server = null);
|
||||||
|
|
||||||
|
public string[] ExecuteServerCommand(string command)
|
||||||
|
{
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
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 bool SetServerDvar(string dvarName, string dvarValue)
|
||||||
|
{
|
||||||
|
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) =>
|
||||||
|
GetClientsAsList().FirstOrDefault(client => client.ClientNumber == clientNumber);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -28,32 +28,32 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="FluentValidation" Version="10.3.6"/>
|
<PackageReference Include="FluentValidation" Version="10.3.6" />
|
||||||
<PackageReference Include="Humanizer.Core" Version="2.13.14"/>
|
<PackageReference Include="Humanizer.Core" Version="2.13.14" />
|
||||||
<PackageReference Include="Humanizer.Core.ru" Version="2.13.14"/>
|
<PackageReference Include="Humanizer.Core.ru" Version="2.13.14" />
|
||||||
<PackageReference Include="Humanizer.Core.de" Version="2.13.14"/>
|
<PackageReference Include="Humanizer.Core.de" Version="2.13.14" />
|
||||||
<PackageReference Include="Humanizer.Core.es" Version="2.13.14"/>
|
<PackageReference Include="Humanizer.Core.es" Version="2.13.14" />
|
||||||
<PackageReference Include="Humanizer.Core.pt" Version="2.13.14"/>
|
<PackageReference Include="Humanizer.Core.pt" Version="2.13.14" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0"/>
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1"/>
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.1"/>
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.1" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0"/>
|
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0"/>
|
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="6.0.1"/>
|
<PackageReference Include="Microsoft.Extensions.Localization" Version="6.0.1" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0"/>
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0"/>
|
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0"/>
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="6.0.0" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1"/>
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||||
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0"/>
|
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
|
||||||
<PackageReference Include="SimpleCrypto.NetCore" Version="1.0.0"/>
|
<PackageReference Include="SimpleCrypto.NetCore" Version="1.0.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ProjectReference Include="..\Data\Data.csproj"/>
|
<ProjectReference Include="..\Data\Data.csproj" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
|
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
|
||||||
<Exec Command="if not exist "$(ProjectDir)..\BUILD" (
if $(ConfigurationName) == Debug (
md "$(ProjectDir)..\BUILD"
)
)
if not exist "$(ProjectDir)..\BUILD\Plugins" (
if $(ConfigurationName) == Debug (
md "$(ProjectDir)..\BUILD\Plugins"
)
)"/>
|
<Exec Command="if not exist "$(ProjectDir)..\BUILD" (
if $(ConfigurationName) == Debug (
md "$(ProjectDir)..\BUILD"
)
)
if not exist "$(ProjectDir)..\BUILD\Plugins" (
if $(ConfigurationName) == Debug (
md "$(ProjectDir)..\BUILD\Plugins"
)
)" />
|
||||||
</Target>
|
</Target>
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
@ -61,7 +61,7 @@
|
|||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<Target DependsOnTargets="BuildOnlySettings;ResolveReferences" Name="CopyProjectReferencesToPackage">
|
<Target DependsOnTargets="BuildOnlySettings;ResolveReferences" Name="CopyProjectReferencesToPackage">
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))"/>
|
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Target>
|
</Target>
|
||||||
|
|
||||||
|
@ -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)
|
public static async Task<T> WithTimeout<T>(this Task<T> task, TimeSpan timeout)
|
||||||
{
|
{
|
||||||
await Task.WhenAny(task, Task.Delay(timeout));
|
await Task.WhenAny(task, Task.Delay(timeout));
|
||||||
|
@ -85,7 +85,7 @@ namespace WebfrontCore.Controllers
|
|||||||
_type.Assembly != excludedAssembly && typeof(IPlugin).IsAssignableFrom(_type));
|
_type.Assembly != excludedAssembly && typeof(IPlugin).IsAssignableFrom(_type));
|
||||||
return pluginType == null ? _translationLookup["WEBFRONT_HELP_COMMAND_NATIVE"] :
|
return pluginType == null ? _translationLookup["WEBFRONT_HELP_COMMAND_NATIVE"] :
|
||||||
pluginType.Name == "ScriptPlugin" ? _translationLookup["WEBFRONT_HELP_SCRIPT_PLUGIN"] :
|
pluginType.Name == "ScriptPlugin" ? _translationLookup["WEBFRONT_HELP_SCRIPT_PLUGIN"] :
|
||||||
Manager.Plugins.First(_plugin => _plugin.GetType().FullName == pluginType.FullName)
|
Manager.Plugins.FirstOrDefault(_plugin => _plugin.GetType().FullName == pluginType.FullName)?
|
||||||
.Name; // for now we're just returning the name of the plugin, maybe later we'll include more info
|
.Name; // for now we're just returning the name of the plugin, maybe later we'll include more info
|
||||||
})
|
})
|
||||||
.Select(_grp => (_grp.Key, _grp.AsEnumerable()));
|
.Select(_grp => (_grp.Key, _grp.AsEnumerable()));
|
||||||
|
Reference in New Issue
Block a user