Compare commits
9 Commits
2022.02.02
...
2022.02.11
Author | SHA1 | Date | |
---|---|---|---|
f3c6b10a35 | |||
4dec284b31 | |||
c9cf7be341 | |||
aa6ae0ab8d | |||
12dfd8c558 | |||
07f675eadc | |||
576d7015fa | |||
b1a1aae6c0 | |||
a0f4ceccfe |
@ -24,7 +24,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<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">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
|
@ -236,13 +236,6 @@ namespace IW4MAdmin.Application
|
||||
.Select(ut => ut.Key)
|
||||
.ToList();
|
||||
|
||||
// this is to prevent the log reader from starting before the initial
|
||||
// query of players on the server
|
||||
if (serverTasksToRemove.Count > 0)
|
||||
{
|
||||
IsInitialized = true;
|
||||
}
|
||||
|
||||
// remove the update tasks as they have completed
|
||||
foreach (var serverId in serverTasksToRemove.Where(serverId => runningUpdateTasks.ContainsKey(serverId)))
|
||||
{
|
||||
@ -419,7 +412,7 @@ namespace IW4MAdmin.Application
|
||||
|
||||
if (!validationResult.IsValid)
|
||||
{
|
||||
throw new ConfigurationException("MANAGER_CONFIGURATION_ERROR")
|
||||
throw new ConfigurationException(_translationLookup["MANAGER_CONFIGURATION_ERROR"])
|
||||
{
|
||||
Errors = validationResult.Errors.Select(_error => _error.ErrorMessage).ToArray(),
|
||||
ConfigurationFileName = ConfigHandler.FileName
|
||||
@ -530,6 +523,7 @@ namespace IW4MAdmin.Application
|
||||
|
||||
Console.WriteLine(_translationLookup["MANAGER_COMMUNICATION_INFO"]);
|
||||
await InitializeServers();
|
||||
IsInitialized = true;
|
||||
}
|
||||
|
||||
private async Task InitializeServers()
|
||||
|
@ -18,14 +18,22 @@ namespace IW4MAdmin.Application.Factories
|
||||
public IGameLogReader CreateGameLogReader(Uri[] logUris, IEventParser eventParser)
|
||||
{
|
||||
var baseUri = logUris[0];
|
||||
if (baseUri.Scheme == Uri.UriSchemeHttp)
|
||||
if (baseUri.Scheme == Uri.UriSchemeHttp || baseUri.Scheme == Uri.UriSchemeHttps)
|
||||
{
|
||||
return new GameLogReaderHttp(logUris, eventParser, _serviceProvider.GetRequiredService<ILogger<GameLogReaderHttp>>());
|
||||
return new GameLogReaderHttp(logUris, eventParser,
|
||||
_serviceProvider.GetRequiredService<ILogger<GameLogReaderHttp>>());
|
||||
}
|
||||
|
||||
else if (baseUri.Scheme == Uri.UriSchemeFile)
|
||||
if (baseUri.Scheme == Uri.UriSchemeFile)
|
||||
{
|
||||
return new GameLogReader(baseUri.LocalPath, eventParser, _serviceProvider.GetRequiredService<ILogger<GameLogReader>>());
|
||||
return new GameLogReader(baseUri.LocalPath, eventParser,
|
||||
_serviceProvider.GetRequiredService<ILogger<GameLogReader>>());
|
||||
}
|
||||
|
||||
if (baseUri.Scheme == Uri.UriSchemeNetTcp)
|
||||
{
|
||||
return new NetworkGameLogReader(logUris, eventParser,
|
||||
_serviceProvider.GetRequiredService<ILogger<NetworkGameLogReader>>());
|
||||
}
|
||||
|
||||
throw new NotImplementedException($"No log reader implemented for Uri scheme \"{baseUri.Scheme}\"");
|
||||
|
@ -6,6 +6,7 @@ using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Data.Models.Client;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@ -30,7 +31,7 @@ namespace IW4MAdmin.Application.Factories
|
||||
|
||||
/// <inheritdoc/>
|
||||
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 argsArray = args.Select(_arg => new CommandArgument
|
||||
@ -40,7 +41,7 @@ namespace IW4MAdmin.Application.Factories
|
||||
}).ToArray();
|
||||
|
||||
return new ScriptCommand(name, alias, description, isTargetRequired, permissionEnum, argsArray, executeAction,
|
||||
_config, _transLookup, _serviceProvider.GetRequiredService<ILogger<ScriptCommand>>());
|
||||
_config, _transLookup, _serviceProvider.GetRequiredService<ILogger<ScriptCommand>>(), supportedGames);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
96
Application/IO/NetworkGameLogReader.cs
Normal file
96
Application/IO/NetworkGameLogReader.cs
Normal file
@ -0,0 +1,96 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
|
||||
namespace IW4MAdmin.Application.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// provides capability of reading log files over HTTP
|
||||
/// </summary>
|
||||
class NetworkGameLogReader : IGameLogReader
|
||||
{
|
||||
private readonly IEventParser _eventParser;
|
||||
private readonly UdpClient _udpClient;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public NetworkGameLogReader(Uri[] uris, IEventParser parser, ILogger<NetworkGameLogReader> logger)
|
||||
{
|
||||
_eventParser = parser;
|
||||
try
|
||||
{
|
||||
var endPoint = new IPEndPoint(Dns.GetHostAddresses(uris[0].Host).First(), uris[0].Port);
|
||||
_udpClient = new UdpClient(endPoint);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Could setup {LogReader}", nameof(NetworkGameLogReader));
|
||||
}
|
||||
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public long Length => -1;
|
||||
|
||||
public int UpdateInterval => 500;
|
||||
|
||||
public async Task<IEnumerable<GameEvent>> ReadEventsFromLog(long fileSizeDiff, long startPosition)
|
||||
{
|
||||
if (_udpClient == null)
|
||||
{
|
||||
return Enumerable.Empty<GameEvent>();
|
||||
}
|
||||
|
||||
byte[] buffer;
|
||||
try
|
||||
{
|
||||
buffer = (await _udpClient.ReceiveAsync()).Buffer;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Could receive lines for {LogReader}", nameof(NetworkGameLogReader));
|
||||
return Enumerable.Empty<GameEvent>();
|
||||
}
|
||||
|
||||
if (!buffer.Any())
|
||||
{
|
||||
return Enumerable.Empty<GameEvent>();
|
||||
}
|
||||
|
||||
var logData = Utilities.EncodingType.GetString(buffer);
|
||||
|
||||
if (string.IsNullOrWhiteSpace(logData))
|
||||
{
|
||||
return Enumerable.Empty<GameEvent>();
|
||||
}
|
||||
|
||||
var lines = logData
|
||||
.Split('\n')
|
||||
.Where(line => line.Length > 0);
|
||||
|
||||
var events = new List<GameEvent>();
|
||||
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 events;
|
||||
}
|
||||
}
|
||||
}
|
@ -311,9 +311,9 @@ namespace IW4MAdmin.Application
|
||||
}
|
||||
|
||||
// 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
|
||||
@ -435,6 +435,7 @@ namespace IW4MAdmin.Application
|
||||
.AddSingleton<IServerDataViewer, ServerDataViewer>()
|
||||
.AddSingleton<IServerDataCollector, ServerDataCollector>()
|
||||
.AddSingleton<IEventPublisher, EventPublisher>()
|
||||
.AddTransient<IScriptPluginTimerHelper, ScriptPluginTimerHelper>()
|
||||
.AddSingleton(translationLookup)
|
||||
.AddDatabaseContextOptions(appConfig);
|
||||
|
||||
|
@ -68,6 +68,29 @@ namespace IW4MAdmin.Application.Misc
|
||||
await ctx.SaveChangesAsync();
|
||||
}
|
||||
|
||||
public async Task SetPersistentMeta(string metaKey, string metaValue, int clientId)
|
||||
{
|
||||
await AddPersistentMeta(metaKey, metaValue, new EFClient { ClientId = clientId });
|
||||
}
|
||||
|
||||
public async Task IncrementPersistentMeta(string metaKey, int incrementAmount, int clientId)
|
||||
{
|
||||
var existingMeta = await GetPersistentMeta(metaKey, new EFClient { ClientId = clientId });
|
||||
|
||||
if (!long.TryParse(existingMeta?.Value ?? "0", out var existingValue))
|
||||
{
|
||||
existingValue = 0;
|
||||
}
|
||||
|
||||
var newValue = existingValue + incrementAmount;
|
||||
await SetPersistentMeta(metaKey, newValue.ToString(), clientId);
|
||||
}
|
||||
|
||||
public async Task DecrementPersistentMeta(string metaKey, int decrementAmount, int clientId)
|
||||
{
|
||||
await IncrementPersistentMeta(metaKey, -decrementAmount, clientId);
|
||||
}
|
||||
|
||||
public async Task AddPersistentMeta(string metaKey, string metaValue)
|
||||
{
|
||||
await using var ctx = _contextFactory.CreateContext();
|
||||
|
@ -6,6 +6,7 @@ using SharedLibraryCore.Interfaces;
|
||||
using System.Linq;
|
||||
using SharedLibraryCore;
|
||||
using IW4MAdmin.Application.API.Master;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
@ -39,24 +40,23 @@ namespace IW4MAdmin.Application.Misc
|
||||
/// <returns></returns>
|
||||
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());
|
||||
|
||||
_logger.LogDebug("Discovered {count} potential script plugins", scriptPluginFiles.Count());
|
||||
|
||||
if (scriptPluginFiles.Count() > 0)
|
||||
{
|
||||
foreach (string fileName in scriptPluginFiles)
|
||||
{
|
||||
_logger.LogDebug("Discovered script plugin {fileName}", fileName);
|
||||
var plugin = new ScriptPlugin(_logger, fileName);
|
||||
yield return plugin;
|
||||
}
|
||||
}
|
||||
return Enumerable.Empty<IPlugin>();
|
||||
}
|
||||
|
||||
var scriptPluginFiles =
|
||||
Directory.GetFiles(pluginDir, "*.js").AsEnumerable().Union(GetRemoteScripts()).ToList();
|
||||
|
||||
_logger.LogDebug("Discovered {count} potential script plugins", scriptPluginFiles.Count);
|
||||
|
||||
return scriptPluginFiles.Select(fileName =>
|
||||
{
|
||||
_logger.LogDebug("Discovered script plugin {fileName}", fileName);
|
||||
return new ScriptPlugin(_logger, fileName);
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
@ -6,7 +6,6 @@ using System;
|
||||
using System.Threading.Tasks;
|
||||
using Data.Models.Client;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using static SharedLibraryCore.Database.Models.EFClient;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
|
||||
namespace IW4MAdmin.Application.Misc
|
||||
@ -16,14 +15,15 @@ namespace IW4MAdmin.Application.Misc
|
||||
/// </summary>
|
||||
public class ScriptCommand : Command
|
||||
{
|
||||
private readonly Action<GameEvent> _executeAction;
|
||||
private readonly Func<GameEvent, Task> _executeAction;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
public ScriptCommand(string name, string alias, string description, bool isTargetRequired, EFClient.Permission permission,
|
||||
CommandArgument[] args, Action<GameEvent> executeAction, CommandConfiguration config, ITranslationLookup layout, ILogger<ScriptCommand> logger)
|
||||
public ScriptCommand(string name, string alias, string description, bool isTargetRequired,
|
||||
EFClient.Permission permission,
|
||||
CommandArgument[] args, Func<GameEvent, Task> executeAction, CommandConfiguration config,
|
||||
ITranslationLookup layout, ILogger<ScriptCommand> logger, Server.Game[] supportedGames)
|
||||
: base(config, layout)
|
||||
{
|
||||
|
||||
_executeAction = executeAction;
|
||||
_logger = logger;
|
||||
Name = name;
|
||||
@ -32,6 +32,7 @@ namespace IW4MAdmin.Application.Misc
|
||||
RequiresTarget = isTargetRequired;
|
||||
Permission = permission;
|
||||
Arguments = args;
|
||||
SupportedGames = supportedGames;
|
||||
}
|
||||
|
||||
public override async Task ExecuteAsync(GameEvent e)
|
||||
@ -43,7 +44,7 @@ namespace IW4MAdmin.Application.Misc
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Run(() => _executeAction(e));
|
||||
await _executeAction(e);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
|
@ -13,6 +13,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jint.Runtime.Interop;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog.Context;
|
||||
using ILogger = Microsoft.Extensions.Logging.ILogger;
|
||||
@ -36,12 +37,12 @@ namespace IW4MAdmin.Application.Misc
|
||||
/// </summary>
|
||||
public bool IsParser { get; private set; }
|
||||
|
||||
public FileSystemWatcher Watcher { get; private set; }
|
||||
public FileSystemWatcher Watcher { get; }
|
||||
|
||||
private Engine _scriptEngine;
|
||||
private readonly string _fileName;
|
||||
private readonly SemaphoreSlim _onProcessing;
|
||||
private bool successfullyLoaded;
|
||||
private readonly SemaphoreSlim _onProcessing = new(1, 1);
|
||||
private bool _successfullyLoaded;
|
||||
private readonly List<string> _registeredCommandNames;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
@ -49,15 +50,14 @@ namespace IW4MAdmin.Application.Misc
|
||||
{
|
||||
_logger = logger;
|
||||
_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,
|
||||
Filter = _fileName.Split(Path.DirectorySeparatorChar).Last()
|
||||
};
|
||||
|
||||
Watcher.EnableRaisingEvents = true;
|
||||
_onProcessing = new SemaphoreSlim(1, 1);
|
||||
_registeredCommandNames = new List<string>();
|
||||
}
|
||||
|
||||
@ -67,12 +67,13 @@ namespace IW4MAdmin.Application.Misc
|
||||
_onProcessing.Dispose();
|
||||
}
|
||||
|
||||
public async Task Initialize(IManager manager, IScriptCommandFactory scriptCommandFactory, IScriptPluginServiceResolver serviceResolver)
|
||||
public async Task Initialize(IManager manager, IScriptCommandFactory scriptCommandFactory,
|
||||
IScriptPluginServiceResolver serviceResolver)
|
||||
{
|
||||
await _onProcessing.WaitAsync();
|
||||
|
||||
try
|
||||
{
|
||||
await _onProcessing.WaitAsync();
|
||||
|
||||
// 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
|
||||
// so if the new file is empty we can't process it yet
|
||||
@ -81,26 +82,27 @@ namespace IW4MAdmin.Application.Misc
|
||||
return;
|
||||
}
|
||||
|
||||
bool firstRun = _scriptEngine == null;
|
||||
var firstRun = _scriptEngine == null;
|
||||
|
||||
// it's been loaded before so we need to call the unload event
|
||||
if (!firstRun)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
_registeredCommandNames.Clear();
|
||||
}
|
||||
|
||||
successfullyLoaded = false;
|
||||
_successfullyLoaded = false;
|
||||
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))
|
||||
{
|
||||
@ -110,45 +112,34 @@ namespace IW4MAdmin.Application.Misc
|
||||
|
||||
_scriptEngine = new Engine(cfg =>
|
||||
cfg.AllowClr(new[]
|
||||
{
|
||||
typeof(System.Net.Http.HttpClient).Assembly,
|
||||
typeof(EFClient).Assembly,
|
||||
typeof(Utilities).Assembly,
|
||||
typeof(Encoding).Assembly
|
||||
})
|
||||
.CatchClrExceptions());
|
||||
|
||||
try
|
||||
{
|
||||
_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");
|
||||
}
|
||||
{
|
||||
typeof(System.Net.Http.HttpClient).Assembly,
|
||||
typeof(EFClient).Assembly,
|
||||
typeof(Utilities).Assembly,
|
||||
typeof(Encoding).Assembly
|
||||
})
|
||||
.CatchClrExceptions()
|
||||
.AddObjectConverter(new PermissionLevelToStringConverter()));
|
||||
|
||||
_scriptEngine.Execute(script);
|
||||
_scriptEngine.SetValue("_localization", Utilities.CurrentLocalization);
|
||||
_scriptEngine.SetValue("_serviceResolver", serviceResolver);
|
||||
dynamic pluginObject = _scriptEngine.GetValue("plugin").ToObject();
|
||||
_scriptEngine.SetValue("_lock", _onProcessing);
|
||||
dynamic pluginObject = _scriptEngine.Evaluate("plugin").ToObject();
|
||||
|
||||
Author = pluginObject.author;
|
||||
Name = pluginObject.name;
|
||||
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)
|
||||
{
|
||||
@ -156,7 +147,7 @@ namespace IW4MAdmin.Application.Misc
|
||||
{
|
||||
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);
|
||||
_registeredCommandNames.Add(command.Name);
|
||||
}
|
||||
@ -164,7 +155,8 @@ namespace IW4MAdmin.Application.Misc
|
||||
|
||||
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);
|
||||
IsParser = true;
|
||||
var eventParser = (IEventParser)_scriptEngine.GetValue("eventParser").ToObject();
|
||||
var rconParser = (IRConParser)_scriptEngine.GetValue("rconParser").ToObject();
|
||||
var eventParser = (IEventParser)_scriptEngine.Evaluate("eventParser").ToObject();
|
||||
var rconParser = (IRConParser)_scriptEngine.Evaluate("rconParser").ToObject();
|
||||
manager.AdditionalEventParsers.Add(eventParser);
|
||||
manager.AdditionalRConParsers.Add(rconParser);
|
||||
}
|
||||
@ -194,27 +186,32 @@ namespace IW4MAdmin.Application.Misc
|
||||
await OnLoadAsync(manager);
|
||||
}
|
||||
|
||||
successfullyLoaded = true;
|
||||
_successfullyLoaded = true;
|
||||
}
|
||||
|
||||
catch (JavaScriptException ex)
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Encountered JavaScript runtime error while executing {methodName} for script plugin {plugin} initialization {@locationInfo}",
|
||||
nameof(OnLoadAsync), _fileName, ex.Location);
|
||||
|
||||
"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 unexpected error while running {methodName} for script plugin {plugin}",
|
||||
nameof(OnLoadAsync), _fileName);
|
||||
|
||||
throw new PluginException("An unexpected error occured while initializing script plugin");
|
||||
}
|
||||
"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)
|
||||
@ -224,42 +221,41 @@ namespace IW4MAdmin.Application.Misc
|
||||
}
|
||||
}
|
||||
|
||||
public async Task OnEventAsync(GameEvent E, Server S)
|
||||
public async Task OnEventAsync(GameEvent gameEvent, Server server)
|
||||
{
|
||||
if (successfullyLoaded)
|
||||
if (_successfullyLoaded)
|
||||
{
|
||||
await _onProcessing.WaitAsync();
|
||||
|
||||
try
|
||||
{
|
||||
_scriptEngine.SetValue("_gameEvent", E);
|
||||
_scriptEngine.SetValue("_server", S);
|
||||
_scriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(S));
|
||||
_scriptEngine.Execute("plugin.onEventAsync(_gameEvent, _server)").GetCompletionValue();
|
||||
await _onProcessing.WaitAsync();
|
||||
_scriptEngine.SetValue("_gameEvent", gameEvent);
|
||||
_scriptEngine.SetValue("_server", server);
|
||||
_scriptEngine.SetValue("_IW4MAdminClient", Utilities.IW4MAdminClient(server));
|
||||
_scriptEngine.Evaluate("plugin.onEventAsync(_gameEvent, _server)");
|
||||
}
|
||||
|
||||
catch (JavaScriptException ex)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", S.ToString()))
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogError(ex,
|
||||
"Encountered JavaScript runtime error while executing {methodName} for script plugin {plugin} with event type {eventType} {@locationInfo}",
|
||||
nameof(OnEventAsync), _fileName, E.Type, ex.Location);
|
||||
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin} with event type {EventType} {@LocationInfo}",
|
||||
nameof(OnEventAsync), Path.GetFileName(_fileName), gameEvent.Type, ex.Location);
|
||||
}
|
||||
|
||||
throw new PluginException($"An error occured while executing action for script plugin");
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
catch (Exception ex)
|
||||
{
|
||||
using (LogContext.PushProperty("Server", S.ToString()))
|
||||
using (LogContext.PushProperty("Server", server.ToString()))
|
||||
{
|
||||
_logger.LogError(e,
|
||||
"Encountered unexpected error while running {methodName} for script plugin {plugin} with event type {eventType}",
|
||||
nameof(OnEventAsync), _fileName, E.Type);
|
||||
_logger.LogError(ex,
|
||||
"Encountered error while running {MethodName} for script plugin {Plugin} with event type {EventType}",
|
||||
nameof(OnEventAsync), _fileName, gameEvent.Type);
|
||||
}
|
||||
|
||||
throw new PluginException($"An error occured while executing action for script plugin");
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
}
|
||||
|
||||
finally
|
||||
@ -272,25 +268,69 @@ namespace IW4MAdmin.Application.Misc
|
||||
}
|
||||
}
|
||||
|
||||
public async Task OnLoadAsync(IManager manager)
|
||||
public 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)
|
||||
try
|
||||
{
|
||||
await Task.FromResult(_scriptEngine.Execute("plugin.onUnloadAsync()").GetCompletionValue());
|
||||
_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
|
||||
{
|
||||
_scriptEngine.Evaluate("plugin.onUnloadAsync()");
|
||||
}
|
||||
catch (JavaScriptException ex)
|
||||
{
|
||||
_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,
|
||||
"Encountered JavaScript runtime error while executing {MethodName} for script plugin {Plugin}",
|
||||
nameof(OnUnloadAsync), Path.GetFileName(_fileName));
|
||||
|
||||
throw new PluginException("An error occured while executing action for script plugin");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -299,9 +339,9 @@ namespace IW4MAdmin.Application.Misc
|
||||
/// <param name="commands">commands value from jint parser</param>
|
||||
/// <param name="scriptCommandFactory">factory to create the command from</param>
|
||||
/// <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
|
||||
foreach (var command in commands.AsArray())
|
||||
@ -311,9 +351,10 @@ namespace IW4MAdmin.Application.Misc
|
||||
string alias = dynamicCommand.alias;
|
||||
string description = dynamicCommand.description;
|
||||
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;
|
||||
|
||||
try
|
||||
@ -344,26 +385,85 @@ namespace IW4MAdmin.Application.Misc
|
||||
}
|
||||
}
|
||||
|
||||
void execute(GameEvent e)
|
||||
try
|
||||
{
|
||||
_scriptEngine.SetValue("_event", e);
|
||||
var jsEventObject = _scriptEngine.GetValue("_event");
|
||||
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
|
||||
{
|
||||
dynamicCommand.execute.Target.Invoke(jsEventObject);
|
||||
await _onProcessing.WaitAsync();
|
||||
|
||||
_scriptEngine.SetValue("_event", gameEvent);
|
||||
var jsEventObject = _scriptEngine.Evaluate("_event");
|
||||
|
||||
dynamicCommand.execute.Target.Invoke(_scriptEngine, jsEventObject);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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 int? DefaultRConPort { get; set; }
|
||||
public string DefaultInstallationDirectoryHint { get; set; }
|
||||
public short FloodProtectInterval { get; set; } = 750;
|
||||
|
||||
public ColorCodeMapping ColorCodeMapping { get; set; } = new ColorCodeMapping
|
||||
{
|
||||
@ -59,4 +60,4 @@ namespace IW4MAdmin.Application.RConParsers
|
||||
MaxPlayersStatus = parserRegexFactory.CreateParserRegex();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
544
GameFiles/IW4x/userraw/scripts/_integration.gsc
Normal file
544
GameFiles/IW4x/userraw/scripts/_integration.gsc
Normal file
@ -0,0 +1,544 @@
|
||||
#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;
|
||||
|
||||
// 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;
|
||||
|
||||
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 );
|
||||
|
||||
self.lastShotCount = currentShotCount;
|
||||
}
|
||||
|
||||
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
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{8C8F3945-0AEF-4949-A1F7-B18E952E50BC}"
|
||||
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
|
||||
DeploymentFiles\deployment-pipeline.yml = DeploymentFiles\deployment-pipeline.yml
|
||||
DeploymentFiles\PostPublish.ps1 = DeploymentFiles\PostPublish.ps1
|
||||
@ -30,8 +29,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProfanityDeterment", "Plugi
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Login", "Plugins\Login\Login.csproj", "{D9F2ED28-6FA5-40CA-9912-E7A849147AB1}"
|
||||
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}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Plugins\ScriptPlugins\ActionOnReport.js = Plugins\ScriptPlugins\ActionOnReport.js
|
||||
@ -52,6 +49,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ScriptPlugins", "ScriptPlug
|
||||
Plugins\ScriptPlugins\ParserCSGO.js = Plugins\ScriptPlugins\ParserCSGO.js
|
||||
Plugins\ScriptPlugins\ParserCSGOSM.js = Plugins\ScriptPlugins\ParserCSGOSM.js
|
||||
Plugins\ScriptPlugins\ParserPlutoniumT4COZM.js = Plugins\ScriptPlugins\ParserPlutoniumT4COZM.js
|
||||
Plugins\ScriptPlugins\GameInterface.js = Plugins\ScriptPlugins\GameInterface.js
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomessageFeed", "Plugins\AutomessageFeed\AutomessageFeed.csproj", "{F5815359-CFC7-44B4-9A3B-C04BACAD5836}"
|
||||
@ -252,30 +250,6 @@ Global
|
||||
{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.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.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
@ -405,7 +379,6 @@ Global
|
||||
{179140D3-97AA-4CB4-8BF6-A0C73CA75701} = {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}
|
||||
{6C706CE5-A206-4E46-8712-F8C48D526091} = {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}
|
||||
{00A1FED2-2254-4AF7-A5DB-2357FA7C88CD} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||
|
@ -64,9 +64,9 @@ namespace Integrations.Cod
|
||||
|
||||
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;
|
||||
@ -150,9 +150,9 @@ namespace Integrations.Cod
|
||||
})
|
||||
{
|
||||
connectionState.SendEventArgs.UserToken = socket;
|
||||
connectionState.OnSentData.Reset();
|
||||
connectionState.OnReceivedData.Reset();
|
||||
connectionState.ConnectionAttempts++;
|
||||
await connectionState.OnSentData.WaitAsync();
|
||||
await connectionState.OnReceivedData.WaitAsync();
|
||||
connectionState.BytesReadPerSegment.Clear();
|
||||
bool exceptionCaught = false;
|
||||
|
||||
@ -199,6 +199,16 @@ namespace Integrations.Cod
|
||||
{
|
||||
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
|
||||
// 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()))
|
||||
{
|
||||
@ -342,7 +353,7 @@ namespace Integrations.Cod
|
||||
|
||||
if (!waitForResponse)
|
||||
{
|
||||
return new byte[0][];
|
||||
return Array.Empty<byte[]>();
|
||||
}
|
||||
|
||||
connectionState.ReceiveEventArgs.SetBuffer(connectionState.ReceiveBuffer);
|
||||
@ -353,12 +364,12 @@ namespace Integrations.Cod
|
||||
if (receiveDataPending)
|
||||
{
|
||||
_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[]
|
||||
{
|
||||
StaticHelpers.SocketTimeout(connectionState.ConnectionAttempts),
|
||||
overrideTimeout
|
||||
}.Max())))
|
||||
}.Max()))
|
||||
{
|
||||
if (connectionState.ConnectionAttempts > 1) // this reduces some spam for unstable connections
|
||||
{
|
||||
@ -407,12 +418,24 @@ namespace Integrations.Cod
|
||||
if (e.BytesTransferred == 0)
|
||||
{
|
||||
_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;
|
||||
}
|
||||
|
||||
if (!(sender is Socket sock))
|
||||
if (sender is not Socket sock)
|
||||
{
|
||||
var semaphore = ActiveQueries[this.Endpoint].OnReceivedData;
|
||||
if (semaphore.CurrentCount == 0)
|
||||
{
|
||||
semaphore.Release();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
@ -427,16 +450,19 @@ namespace Integrations.Cod
|
||||
try
|
||||
{
|
||||
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
|
||||
while (sock.Available > 0)
|
||||
{
|
||||
_log.LogDebug("{available} more bytes to be read", sock.Available);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
@ -447,27 +473,39 @@ namespace Integrations.Cod
|
||||
_log.LogDebug("Remaining bytes are async");
|
||||
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
|
||||
state.BytesReadPerSegment.Add(state.ReceiveEventArgs.BytesTransferred);
|
||||
totalBytesTransferred += state.ReceiveEventArgs.BytesTransferred;
|
||||
}
|
||||
|
||||
ActiveQueries[this.Endpoint].OnReceivedData.Set();
|
||||
}
|
||||
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
_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)
|
||||
{
|
||||
_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,11 +21,12 @@ namespace Integrations.Cod
|
||||
private const int BufferSize = 16384;
|
||||
public readonly byte[] ReceiveBuffer = new byte[BufferSize];
|
||||
public readonly SemaphoreSlim OnComplete = new SemaphoreSlim(1, 1);
|
||||
public readonly ManualResetEventSlim OnSentData = new ManualResetEventSlim(false);
|
||||
public readonly ManualResetEventSlim OnReceivedData = new ManualResetEventSlim(false);
|
||||
public readonly SemaphoreSlim OnSentData = new(1, 1);
|
||||
public readonly SemaphoreSlim OnReceivedData = new (1, 1);
|
||||
|
||||
public List<int> BytesReadPerSegment { get; set; } = new List<int>();
|
||||
public SocketAsyncEventArgs SendEventArgs { get; set; } = new SocketAsyncEventArgs();
|
||||
public SocketAsyncEventArgs ReceiveEventArgs { get; set; } = new SocketAsyncEventArgs();
|
||||
public DateTime LastQuery { get; set; } = DateTime.Now;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -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());
|
||||
}
|
||||
}
|
430
Plugins/ScriptPlugins/GameInterface.js
Normal file
430
Plugins/ScriptPlugins/GameInterface.js
Normal file
@ -0,0 +1,430 @@
|
||||
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) => {
|
||||
const eventType = eventTypes[gameEvent.Type];
|
||||
|
||||
if (servers[server.EndPoint] != null && !servers[server.EndPoint].enabled) {
|
||||
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] == 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 <= 30) {
|
||||
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');
|
||||
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) {
|
||||
servers[server.EndPoint] = {
|
||||
enabled: false
|
||||
}
|
||||
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,
|
||||
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 = {
|
||||
author: 'RaidMax',
|
||||
version: 0.5,
|
||||
version: 0.6,
|
||||
name: 'IW4x Parser',
|
||||
isParser: true,
|
||||
|
||||
@ -20,10 +20,11 @@ var plugin = {
|
||||
rconParser.Configuration.CommandPrefixes.Ban = 'clientkick {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.TempBan = 'tempbanclient {0} "{1}"';
|
||||
|
||||
rconParser.Configuration.DefaultRConPort = 28960;
|
||||
rconParser.Configuration.DefaultInstallationDirectoryHint = 'HKEY_CURRENT_USER\\Software\\Classes\\iw4x\\shell\\open\\command';
|
||||
rconParser.Configuration.DefaultRConPort = 28960;
|
||||
rconParser.Configuration.DefaultInstallationDirectoryHint = 'HKEY_CURRENT_USER\\Software\\Classes\\iw4x\\shell\\open\\command';
|
||||
rconParser.Configuration.FloodProtectInterval = 150;
|
||||
|
||||
eventParser.Configuration.GameDirectory = 'userraw';
|
||||
eventParser.Configuration.GameDirectory = 'userraw';
|
||||
|
||||
rconParser.Version = 'IW4x (v0.6.0)';
|
||||
rconParser.GameName = 2; // IW4x
|
||||
@ -37,4 +38,4 @@ var plugin = {
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
||||
};
|
||||
|
@ -249,7 +249,7 @@ namespace SharedLibraryCore
|
||||
}
|
||||
|
||||
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 Message;
|
||||
public EFClient Origin;
|
||||
@ -260,10 +260,14 @@ namespace SharedLibraryCore
|
||||
|
||||
public GameEvent()
|
||||
{
|
||||
_eventFinishedWaiter = new ManualResetEvent(false);
|
||||
Time = DateTime.UtcNow;
|
||||
Id = GetNextEventId();
|
||||
}
|
||||
|
||||
~GameEvent()
|
||||
{
|
||||
_eventFinishedWaiter.Dispose();
|
||||
}
|
||||
|
||||
public EventSource Source { get; set; }
|
||||
|
||||
@ -299,15 +303,12 @@ namespace SharedLibraryCore
|
||||
return Interlocked.Increment(ref NextEventId);
|
||||
}
|
||||
|
||||
~GameEvent()
|
||||
{
|
||||
_eventFinishedWaiter.Set();
|
||||
_eventFinishedWaiter.Dispose();
|
||||
}
|
||||
|
||||
public void Complete()
|
||||
{
|
||||
_eventFinishedWaiter.Set();
|
||||
if (_eventFinishedWaiter.CurrentCount == 0)
|
||||
{
|
||||
_eventFinishedWaiter.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<GameEvent> WaitAsync()
|
||||
@ -325,7 +326,7 @@ namespace SharedLibraryCore
|
||||
Utilities.DefaultLogger.LogDebug("Begin wait for event {Id}", Id);
|
||||
try
|
||||
{
|
||||
processed = await Task.Run(() => _eventFinishedWaiter.WaitOne(timeSpan), token);
|
||||
processed = await _eventFinishedWaiter.WaitAsync(timeSpan, token);
|
||||
}
|
||||
|
||||
catch (TaskCanceledException)
|
||||
@ -347,4 +348,4 @@ namespace SharedLibraryCore
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -19,6 +19,35 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <returns></returns>
|
||||
Task AddPersistentMeta(string metaKey, string metaValue, EFClient client, EFMeta linkedMeta = null);
|
||||
|
||||
/// <summary>
|
||||
/// adds or updates meta key and value to the database
|
||||
/// </summary>
|
||||
/// <param name="metaKey">key of meta data</param>
|
||||
/// <param name="metaValue">value of the meta data</param>
|
||||
/// <param name="clientId">id of the client to save the meta for</param>
|
||||
/// <returns></returns>
|
||||
Task SetPersistentMeta(string metaKey, string metaValue, int clientId);
|
||||
|
||||
/// <summary>
|
||||
/// increments meta value and persists to the database
|
||||
/// <remarks>if the meta value does not already exist it will be set to the increment amount</remarks>
|
||||
/// </summary>
|
||||
/// <param name="metaKey">key of meta data</param>
|
||||
/// <param name="incrementAmount">value to increment by</param>
|
||||
/// <param name="clientId">id of the client to save the meta for</param>
|
||||
/// <returns></returns>
|
||||
Task IncrementPersistentMeta(string metaKey, int incrementAmount, int clientId);
|
||||
|
||||
/// <summary>
|
||||
/// decrements meta value and persists to the database
|
||||
/// <remarks>if the meta value does not already exist it will be set to the decrement amount</remarks>
|
||||
/// </summary>
|
||||
/// <param name="metaKey">key of meta data</param>
|
||||
/// <param name="decrementAmount">value to increment by</param>
|
||||
/// <param name="clientId">id of the client to save the meta for</param>
|
||||
/// <returns></returns>
|
||||
Task DecrementPersistentMeta(string metaKey, int decrementAmount, int clientId);
|
||||
|
||||
/// <summary>
|
||||
/// adds or updates meta key and value to the database
|
||||
/// </summary>
|
||||
@ -82,4 +111,4 @@ namespace SharedLibraryCore.Interfaces
|
||||
Task<IEnumerable<T>> GetRuntimeMeta<T>(ClientPaginationRequest request, MetaType metaType)
|
||||
where T : IClientMeta;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
bool IsParser => false;
|
||||
Task OnLoadAsync(IManager manager);
|
||||
Task OnUnloadAsync();
|
||||
Task OnEventAsync(GameEvent E, Server S);
|
||||
Task OnEventAsync(GameEvent gameEvent, Server server);
|
||||
Task OnTickAsync(Server S);
|
||||
}
|
||||
}
|
@ -20,4 +20,4 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <returns>initialized script plugin collection</returns>
|
||||
IEnumerable<IPlugin> DiscoverScriptPlugins();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -100,5 +100,7 @@ namespace SharedLibraryCore.Interfaces
|
||||
string DefaultInstallationDirectoryHint { get; }
|
||||
|
||||
ColorCodeMapping ColorCodeMapping { get; }
|
||||
|
||||
short FloodProtectInterval { get; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SharedLibraryCore.Interfaces
|
||||
{
|
||||
@ -18,8 +19,10 @@ namespace SharedLibraryCore.Interfaces
|
||||
/// <param name="isTargetRequired">target required or not</param>
|
||||
/// <param name="args">command arguments (name, is required)</param>
|
||||
/// <param name="executeAction">action to peform when commmand is executed</param>
|
||||
/// <param name="supportedGames"></param>
|
||||
/// <returns></returns>
|
||||
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,23 @@ namespace SharedLibraryCore
|
||||
}
|
||||
|
||||
public abstract Task<long> GetIdForServer(Server server = null);
|
||||
|
||||
public string[] ExecuteServerCommand(string command)
|
||||
{
|
||||
return this.ExecuteCommandAsync(command).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public string GetServerDvar(string dvarName)
|
||||
{
|
||||
return this.GetDvarAsync<string>(dvarName).GetAwaiter().GetResult()?.Value;
|
||||
}
|
||||
|
||||
public void SetServerDvar(string dvarName, string dvarValue)
|
||||
{
|
||||
this.SetDvarAsync(dvarName, dvarValue).GetAwaiter().GetResult();
|
||||
}
|
||||
|
||||
public EFClient GetClientByNumber(int clientNumber) =>
|
||||
GetClientsAsList().FirstOrDefault(client => client.ClientNumber == clientNumber);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -28,32 +28,32 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation" Version="10.3.6"/>
|
||||
<PackageReference Include="Humanizer.Core" 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.es" 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.EntityFrameworkCore" 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.Json" Version="6.0.0"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="6.0.1"/>
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" 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="Newtonsoft.Json" Version="13.0.1"/>
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0"/>
|
||||
<PackageReference Include="SimpleCrypto.NetCore" Version="1.0.0"/>
|
||||
<PackageReference Include="FluentValidation" Version="10.3.6" />
|
||||
<PackageReference Include="Humanizer.Core" 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.es" 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.EntityFrameworkCore" 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.Json" Version="6.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Localization" Version="6.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Logging.Console" 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="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="4.1.0" />
|
||||
<PackageReference Include="SimpleCrypto.NetCore" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Data\Data.csproj"/>
|
||||
<ProjectReference Include="..\Data\Data.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<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>
|
||||
|
||||
<PropertyGroup>
|
||||
@ -61,7 +61,7 @@
|
||||
</PropertyGroup>
|
||||
<Target DependsOnTargets="BuildOnlySettings;ResolveReferences" Name="CopyProjectReferencesToPackage">
|
||||
<ItemGroup>
|
||||
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))"/>
|
||||
<BuildOutputInPackage Include="@(ReferenceCopyLocalPaths->WithMetadataValue('ReferenceSourceTarget', 'ProjectReference'))" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
|
@ -85,7 +85,7 @@ namespace WebfrontCore.Controllers
|
||||
_type.Assembly != excludedAssembly && typeof(IPlugin).IsAssignableFrom(_type));
|
||||
return pluginType == null ? _translationLookup["WEBFRONT_HELP_COMMAND_NATIVE"] :
|
||||
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
|
||||
})
|
||||
.Select(_grp => (_grp.Key, _grp.AsEnumerable()));
|
||||
@ -93,4 +93,4 @@ namespace WebfrontCore.Controllers
|
||||
return View(commands);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user