add ability to register custom event generators for event parsers / truncate long client names fix

This commit is contained in:
RaidMax 2020-04-04 12:40:23 -05:00
parent 9fdf4bad9c
commit 36af673fc7
24 changed files with 334 additions and 69 deletions

View File

@ -44,6 +44,7 @@ namespace IW4MAdmin.Application
public bool IsRestartRequested { get; private set; } public bool IsRestartRequested { get; private set; }
public IMiddlewareActionHandler MiddlewareActionHandler { get; } public IMiddlewareActionHandler MiddlewareActionHandler { get; }
private readonly List<IManagerCommand> _commands; private readonly List<IManagerCommand> _commands;
private readonly ILogger _logger;
private readonly List<MessageToken> MessageTokens; private readonly List<MessageToken> MessageTokens;
private readonly ClientService ClientSvc; private readonly ClientService ClientSvc;
readonly AliasService AliasSvc; readonly AliasService AliasSvc;
@ -60,11 +61,12 @@ namespace IW4MAdmin.Application
private readonly IConfigurationHandler<CommandConfiguration> _commandConfiguration; private readonly IConfigurationHandler<CommandConfiguration> _commandConfiguration;
private readonly IGameServerInstanceFactory _serverInstanceFactory; private readonly IGameServerInstanceFactory _serverInstanceFactory;
private readonly IParserRegexFactory _parserRegexFactory; private readonly IParserRegexFactory _parserRegexFactory;
private readonly IEnumerable<IRegisterEvent> _customParserEvents;
public ApplicationManager(ILogger logger, IMiddlewareActionHandler actionHandler, IEnumerable<IManagerCommand> commands, public ApplicationManager(ILogger logger, IMiddlewareActionHandler actionHandler, IEnumerable<IManagerCommand> commands,
ITranslationLookup translationLookup, IConfigurationHandler<CommandConfiguration> commandConfiguration, ITranslationLookup translationLookup, IConfigurationHandler<CommandConfiguration> commandConfiguration,
IConfigurationHandler<ApplicationConfiguration> appConfigHandler, IGameServerInstanceFactory serverInstanceFactory, IConfigurationHandler<ApplicationConfiguration> appConfigHandler, IGameServerInstanceFactory serverInstanceFactory,
IEnumerable<IPlugin> plugins, IParserRegexFactory parserRegexFactory) IEnumerable<IPlugin> plugins, IParserRegexFactory parserRegexFactory, IEnumerable<IRegisterEvent> customParserEvents)
{ {
MiddlewareActionHandler = actionHandler; MiddlewareActionHandler = actionHandler;
_servers = new ConcurrentBag<Server>(); _servers = new ConcurrentBag<Server>();
@ -75,9 +77,10 @@ namespace IW4MAdmin.Application
ConfigHandler = appConfigHandler; ConfigHandler = appConfigHandler;
StartTime = DateTime.UtcNow; StartTime = DateTime.UtcNow;
PageList = new PageList(); PageList = new PageList();
AdditionalEventParsers = new List<IEventParser>() { new BaseEventParser(parserRegexFactory) }; AdditionalEventParsers = new List<IEventParser>() { new BaseEventParser(parserRegexFactory, logger) };
AdditionalRConParsers = new List<IRConParser>() { new BaseRConParser(parserRegexFactory) }; AdditionalRConParsers = new List<IRConParser>() { new BaseRConParser(parserRegexFactory) };
TokenAuthenticator = new TokenAuthentication(); TokenAuthenticator = new TokenAuthentication();
_logger = logger;
_metaService = new MetaService(); _metaService = new MetaService();
_tokenSource = new CancellationTokenSource(); _tokenSource = new CancellationTokenSource();
_loggers.Add(0, logger); _loggers.Add(0, logger);
@ -86,6 +89,7 @@ namespace IW4MAdmin.Application
_commandConfiguration = commandConfiguration; _commandConfiguration = commandConfiguration;
_serverInstanceFactory = serverInstanceFactory; _serverInstanceFactory = serverInstanceFactory;
_parserRegexFactory = parserRegexFactory; _parserRegexFactory = parserRegexFactory;
_customParserEvents = customParserEvents;
Plugins = plugins; Plugins = plugins;
} }
@ -557,6 +561,16 @@ namespace IW4MAdmin.Application
MetaService.AddRuntimeMeta(getPenaltyMeta); MetaService.AddRuntimeMeta(getPenaltyMeta);
#endregion #endregion
#region CUSTOM_EVENTS
foreach (var customEvent in _customParserEvents.SelectMany(_events => _events.Events))
{
foreach (var parser in AdditionalEventParsers)
{
parser.RegisterCustomEvent(customEvent.Item1, customEvent.Item2, customEvent.Item3);
}
}
#endregion
await InitializeServers(); await InitializeServers();
} }
@ -781,7 +795,7 @@ namespace IW4MAdmin.Application
public IEventParser GenerateDynamicEventParser(string name) public IEventParser GenerateDynamicEventParser(string name)
{ {
return new DynamicEventParser(_parserRegexFactory) return new DynamicEventParser(_parserRegexFactory, _logger)
{ {
Name = name Name = name
}; };

View File

@ -2,6 +2,7 @@
using SharedLibraryCore.Database.Models; using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using System; using System;
using System.Collections.Generic;
using System.Linq; using System.Linq;
using static SharedLibraryCore.Server; using static SharedLibraryCore.Server;
@ -9,8 +10,14 @@ namespace IW4MAdmin.Application.EventParsers
{ {
public class BaseEventParser : IEventParser public class BaseEventParser : IEventParser
{ {
public BaseEventParser(IParserRegexFactory parserRegexFactory) private readonly Dictionary<string, (string, Func<string, IEventParserConfiguration, GameEvent, GameEvent>)> _customEventRegistrations;
private readonly ILogger _logger;
public BaseEventParser(IParserRegexFactory parserRegexFactory, ILogger logger)
{ {
_customEventRegistrations = new Dictionary<string, (string, Func<string, IEventParserConfiguration, GameEvent, GameEvent>)>();
_logger = logger;
Configuration = new DynamicEventParserConfiguration(parserRegexFactory) Configuration = new DynamicEventParserConfiguration(parserRegexFactory)
{ {
GameDirectory = "main", GameDirectory = "main",
@ -272,51 +279,25 @@ namespace IW4MAdmin.Application.EventParsers
}; };
} }
// this is a custom event printed out by _customcallbacks.gsc (used for team balance) if (_customEventRegistrations.ContainsKey(eventType))
if (eventType == "JoinTeam")
{ {
return new GameEvent() var eventModifier = _customEventRegistrations[eventType];
try
{ {
Type = GameEvent.EventType.JoinTeam, return eventModifier.Item2(logLine, Configuration, new GameEvent()
{
Type = GameEvent.EventType.Other,
Data = logLine, Data = logLine,
Origin = new EFClient() { NetworkId = lineSplit[1].ConvertGuidToLong(Configuration.GuidNumberStyle) }, Subtype = eventModifier.Item1,
RequiredEntity = GameEvent.EventRequiredEntity.Target,
GameTime = gameTime GameTime = gameTime
}; });
} }
// this is a custom event printed out by _customcallbacks.gsc (used for anticheat) catch (Exception e)
if (eventType == "ScriptKill")
{ {
long originId = lineSplit[1].ConvertGuidToLong(Configuration.GuidNumberStyle, 1); _logger.WriteWarning($"Could not handle custom event generation - {e.GetExceptionInfo()}");
long targetId = lineSplit[2].ConvertGuidToLong(Configuration.GuidNumberStyle, 1);
return new GameEvent()
{
Type = GameEvent.EventType.ScriptKill,
Data = logLine,
Origin = new EFClient() { NetworkId = originId },
Target = new EFClient() { NetworkId = targetId },
RequiredEntity = GameEvent.EventRequiredEntity.Origin | GameEvent.EventRequiredEntity.Target,
GameTime = gameTime
};
} }
// this is a custom event printed out by _customcallbacks.gsc (used for anticheat)
if (eventType == "ScriptDamage")
{
long originId = lineSplit[1].ConvertGuidToLong(Configuration.GuidNumberStyle, 1);
long targetId = lineSplit[2].ConvertGuidToLong(Configuration.GuidNumberStyle, 1);
return new GameEvent()
{
Type = GameEvent.EventType.ScriptDamage,
Data = logLine,
Origin = new EFClient() { NetworkId = originId },
Target = new EFClient() { NetworkId = targetId },
RequiredEntity = GameEvent.EventRequiredEntity.Origin | GameEvent.EventRequiredEntity.Target,
GameTime = gameTime
};
} }
return new GameEvent() return new GameEvent()
@ -329,5 +310,31 @@ namespace IW4MAdmin.Application.EventParsers
GameTime = gameTime GameTime = gameTime
}; };
} }
/// <inheritdoc/>
public void RegisterCustomEvent(string eventSubtype, string eventTriggerValue, Func<string, IEventParserConfiguration, GameEvent, GameEvent> eventModifier)
{
if (string.IsNullOrWhiteSpace(eventSubtype))
{
throw new ArgumentException("Event subtype cannot be empty");
}
if (string.IsNullOrWhiteSpace(eventTriggerValue))
{
throw new ArgumentException("Event trigger value cannot be empty");
}
if (eventModifier == null)
{
throw new ArgumentException("Event modifier must be specified");
}
if (_customEventRegistrations.ContainsKey(eventTriggerValue))
{
throw new ArgumentException($"Event trigger value '{eventTriggerValue}' is already registered");
}
_customEventRegistrations.Add(eventTriggerValue, (eventSubtype, eventModifier));
}
} }
} }

View File

@ -8,7 +8,7 @@ namespace IW4MAdmin.Application.EventParsers
/// </summary> /// </summary>
sealed internal class DynamicEventParser : BaseEventParser sealed internal class DynamicEventParser : BaseEventParser
{ {
public DynamicEventParser(IParserRegexFactory parserRegexFactory) : base(parserRegexFactory) public DynamicEventParser(IParserRegexFactory parserRegexFactory, ILogger logger) : base(parserRegexFactory, logger)
{ {
} }
} }

View File

@ -321,6 +321,18 @@ namespace IW4MAdmin.Application
serviceCollection.AddSingleton(scriptPlugin); serviceCollection.AddSingleton(scriptPlugin);
} }
// register any eventable types
foreach (var assemblyType in typeof(Program).Assembly.GetTypes()
.Where(_asmType => typeof(IRegisterEvent).IsAssignableFrom(_asmType))
.Union(pluginImplementations
.Item1.SelectMany(_asm => _asm.Assembly.GetTypes())
.Distinct()
.Where(_asmType => typeof(IRegisterEvent).IsAssignableFrom(_asmType))))
{
var instance = Activator.CreateInstance(assemblyType) as IRegisterEvent;
serviceCollection.AddSingleton(instance);
}
return serviceCollection; return serviceCollection;
} }
} }

View File

@ -10,7 +10,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" /> <PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2" />
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -10,7 +10,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -16,7 +16,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -23,7 +23,7 @@
</Target> </Target>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -16,7 +16,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -0,0 +1,94 @@
using SharedLibraryCore;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Interfaces;
using System.Collections.Generic;
using EventGeneratorCallback = System.ValueTuple<string, string,
System.Func<string, SharedLibraryCore.Interfaces.IEventParserConfiguration,
SharedLibraryCore.GameEvent,
SharedLibraryCore.GameEvent>>;
namespace IW4MAdmin.Plugins.Stats.Events
{
public class Script : IRegisterEvent
{
private const string EVENT_SCRIPTKILL = "ScriptKill";
private const string EVENT_SCRIPTDAMAGE = "ScriptDamage";
private const string EVENT_JOINTEAM = "JoinTeam";
/// <summary>
/// this is a custom event printed out by _customcallbacks.gsc (used for anticheat)
/// </summary>
/// <returns></returns>
private EventGeneratorCallback ScriptKill()
{
return (EVENT_SCRIPTKILL, EVENT_SCRIPTKILL, (string eventLine, IEventParserConfiguration config, GameEvent autoEvent) =>
{
string[] lineSplit = eventLine.Split(";");
long originId = lineSplit[1].ConvertGuidToLong(config.GuidNumberStyle, 1);
long targetId = lineSplit[2].ConvertGuidToLong(config.GuidNumberStyle, 1);
autoEvent.Type = GameEvent.EventType.ScriptKill;
autoEvent.Origin = new EFClient() { NetworkId = originId };
autoEvent.Target = new EFClient() { NetworkId = targetId };
autoEvent.RequiredEntity = GameEvent.EventRequiredEntity.Origin | GameEvent.EventRequiredEntity.Target;
autoEvent.GameTime = autoEvent.GameTime;
return autoEvent;
}
);
}
/// <summary>
/// this is a custom event printed out by _customcallbacks.gsc (used for anticheat)
/// </summary>
/// <returns></returns>
private EventGeneratorCallback ScriptDamage()
{
// this is a custom event printed out by _customcallbacks.gsc (used for anticheat)
return (EVENT_SCRIPTDAMAGE, EVENT_SCRIPTDAMAGE, (string eventLine, IEventParserConfiguration config, GameEvent autoEvent) =>
{
string[] lineSplit = eventLine.Split(";");
long originId = lineSplit[1].ConvertGuidToLong(config.GuidNumberStyle, 1);
long targetId = lineSplit[2].ConvertGuidToLong(config.GuidNumberStyle, 1);
autoEvent.Type = GameEvent.EventType.ScriptDamage;
autoEvent.Origin = new EFClient() { NetworkId = originId };
autoEvent.Target = new EFClient() { NetworkId = targetId };
autoEvent.RequiredEntity = GameEvent.EventRequiredEntity.Origin | GameEvent.EventRequiredEntity.Target;
return autoEvent;
}
);
}
/// <summary>
/// this is a custom event printed out by _customcallbacks.gsc (used for anticheat)
/// </summary>
/// <returns></returns>
private EventGeneratorCallback JoinTeam()
{
// this is a custom event printed out by _customcallbacks.gsc (used for anticheat)
return (EVENT_JOINTEAM, EVENT_JOINTEAM, (string eventLine, IEventParserConfiguration config, GameEvent autoEvent) =>
{
string[] lineSplit = eventLine.Split(";");
long originId = lineSplit[1].ConvertGuidToLong(config.GuidNumberStyle, 1);
long targetId = lineSplit[2].ConvertGuidToLong(config.GuidNumberStyle, 1);
autoEvent.Type = GameEvent.EventType.JoinTeam;
autoEvent.Origin = new EFClient() { NetworkId = lineSplit[1].ConvertGuidToLong(config.GuidNumberStyle) };
autoEvent.RequiredEntity = GameEvent.EventRequiredEntity.Target;
return autoEvent;
}
);
}
public IEnumerable<EventGeneratorCallback> Events =>
new[]
{
ScriptKill(),
ScriptDamage(),
JoinTeam()
};
}
}

View File

@ -16,7 +16,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Target Name="PostBuild" AfterTargets="PostBuildEvent">

View File

@ -14,7 +14,7 @@
<RunPostBuildEvent>Always</RunPostBuildEvent> <RunPostBuildEvent>Always</RunPostBuildEvent>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.7" PrivateAssets="All" /> <PackageReference Include="RaidMax.IW4MAdmin.SharedLibraryCore" Version="2.2.8" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -13,13 +13,16 @@ namespace SharedLibraryCore.Database.Models
[ForeignKey("LinkId")] [ForeignKey("LinkId")]
public virtual EFAliasLink Link { get; set; } public virtual EFAliasLink Link { get; set; }
[Required] [Required]
[MaxLength(24)] [MaxLength(MAX_NAME_LENGTH)]
public string Name { get; set; } public string Name { get; set; }
[MaxLength(24)] [MaxLength(MAX_NAME_LENGTH)]
public string SearchableName { get; set; } public string SearchableName { get; set; }
[Required] [Required]
public int? IPAddress { get; set; } public int? IPAddress { get; set; }
[Required] [Required]
public DateTime DateAdded { get; set; } public DateTime DateAdded { get; set; }
[NotMapped]
public const int MAX_NAME_LENGTH = 24;
} }
} }

View File

@ -214,6 +214,10 @@ namespace SharedLibraryCore
} }
public EventType Type; public EventType Type;
/// <summary>
/// suptype of the event for more detailed classification
/// </summary>
public string Subtype { get; set; }
public EventRequiredEntity RequiredEntity { get; set; } public EventRequiredEntity RequiredEntity { get; set; }
public string Data; // Data is usually the message sent by player public string Data; // Data is usually the message sent by player
public string Message; public string Message;

View File

@ -1,4 +1,5 @@
using static SharedLibraryCore.Server; using System;
using static SharedLibraryCore.Server;
namespace SharedLibraryCore.Interfaces namespace SharedLibraryCore.Interfaces
{ {
@ -33,8 +34,16 @@ namespace SharedLibraryCore.Interfaces
string URLProtocolFormat { get; set; } string URLProtocolFormat { get; set; }
/// <summary> /// <summary>
/// Specifies the text name of the game the parser is for /// specifies the text name of the game the parser is for
/// </summary> /// </summary>
string Name { get; set; } string Name { get; set; }
/// <summary>
/// registers a custom event subtype to be triggered when a value is detected
/// </summary>
/// <param name="eventSubtype">subtype assigned to the event when generated</param>
/// <param name="eventTriggerValue">event keyword to trigger an event generation</param>
/// <param name="eventModifier">function pointer that modifies the generated game event</param>
void RegisterCustomEvent(string eventSubtype, string eventTriggerValue, Func<string, IEventParserConfiguration, GameEvent, GameEvent> eventModifier);
} }
} }

View File

@ -1,4 +1,5 @@
using System.Globalization; using System.Collections.Generic;
using System.Globalization;
namespace SharedLibraryCore.Interfaces namespace SharedLibraryCore.Interfaces
{ {

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace SharedLibraryCore.Interfaces
{
/// <summary>
/// interface defining the capabilities of a custom event registration
/// </summary>
public interface IRegisterEvent
{
/// <summary>
/// collection of custom event registrations
/// <remarks>
/// (Subtype, trigger value, event generator)
/// </remarks>
/// </summary>
IEnumerable<(string, string, Func<string, IEventParserConfiguration, GameEvent, GameEvent>)> Events { get; }
}
}

View File

@ -18,6 +18,7 @@ namespace SharedLibraryCore.Services
{ {
int? linkId = null; int? linkId = null;
int? aliasId = null; int? aliasId = null;
entity.Name = entity.Name.CapClientName(EFAlias.MAX_NAME_LENGTH);
if (entity.IPAddress != null) if (entity.IPAddress != null)
{ {
@ -102,8 +103,10 @@ namespace SharedLibraryCore.Services
} }
} }
private async Task UpdateAlias(string name, int? ip, EFClient entity, DatabaseContext context) private async Task UpdateAlias(string originalName, int? ip, EFClient entity, DatabaseContext context)
{ {
string name = originalName.CapClientName(EFAlias.MAX_NAME_LENGTH);
// entity is the tracked db context item // entity is the tracked db context item
// get all aliases by IP address and LinkId // get all aliases by IP address and LinkId
var iqAliases = context.Aliases var iqAliases = context.Aliases

View File

@ -6,7 +6,7 @@
<ApplicationIcon /> <ApplicationIcon />
<StartupObject /> <StartupObject />
<PackageId>RaidMax.IW4MAdmin.SharedLibraryCore</PackageId> <PackageId>RaidMax.IW4MAdmin.SharedLibraryCore</PackageId>
<Version>2.2.7</Version> <Version>2.2.8</Version>
<Authors>RaidMax</Authors> <Authors>RaidMax</Authors>
<Company>Forever None</Company> <Company>Forever None</Company>
<Configurations>Debug;Release;Prerelease</Configurations> <Configurations>Debug;Release;Prerelease</Configurations>
@ -15,13 +15,13 @@
<PackageTags>IW4MAdmin</PackageTags> <PackageTags>IW4MAdmin</PackageTags>
<RepositoryUrl>https://github.com/RaidMax/IW4M-Admin/</RepositoryUrl> <RepositoryUrl>https://github.com/RaidMax/IW4M-Admin/</RepositoryUrl>
<PackageProjectUrl>https://www.raidmax.org/IW4MAdmin/</PackageProjectUrl> <PackageProjectUrl>https://www.raidmax.org/IW4MAdmin/</PackageProjectUrl>
<Copyright>2019</Copyright> <Copyright>2020</Copyright>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance> <PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageLicenseExpression>MIT</PackageLicenseExpression> <PackageLicenseExpression>MIT</PackageLicenseExpression>
<Description>Shared Library for IW4MAdmin</Description> <Description>Shared Library for IW4MAdmin</Description>
<AssemblyVersion>2.2.7.0</AssemblyVersion> <AssemblyVersion>2.2.8.0</AssemblyVersion>
<FileVersion>2.2.7.0</FileVersion> <FileVersion>2.2.8.0</FileVersion>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Prerelease|AnyCPU'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Prerelease|AnyCPU'">

View File

@ -94,6 +94,18 @@ namespace SharedLibraryCore
return newStr; return newStr;
} }
/// <summary>
/// caps client name to the specified character length - 3
/// and adds ellipses to the end of the reamining client name
/// </summary>
/// <param name="str">client name</param>
/// <param name="maxLength">max number of characters for the name</param>
/// <returns></returns>
public static string CapClientName(this string str, int maxLength) =>
str.Length > maxLength ?
$"{str.Substring(0, maxLength - 3)}..." :
str;
/// <summary> /// <summary>
/// helper method to get the information about an exception and inner exceptions /// helper method to get the information about an exception and inner exceptions
/// </summary> /// </summary>

View File

@ -1,4 +1,5 @@
using ApplicationTests.Fixtures; using ApplicationTests.Fixtures;
using FakeItEasy;
using IW4MAdmin.Application.EventParsers; using IW4MAdmin.Application.EventParsers;
using IW4MAdmin.Application.Factories; using IW4MAdmin.Application.Factories;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@ -7,6 +8,7 @@ using NUnit.Framework;
using SharedLibraryCore; using SharedLibraryCore;
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using System; using System;
using static SharedLibraryCore.GameEvent;
namespace ApplicationTests namespace ApplicationTests
{ {
@ -15,15 +17,19 @@ namespace ApplicationTests
{ {
private EventLogTest eventLogData; private EventLogTest eventLogData;
private IServiceProvider serviceProvider; private IServiceProvider serviceProvider;
private ILogger fakeLogger;
[SetUp] [SetUp]
public void Setup() public void Setup()
{ {
eventLogData = JsonConvert.DeserializeObject<EventLogTest>(System.IO.File.ReadAllText("Files/GameEvents.json")); eventLogData = JsonConvert.DeserializeObject<EventLogTest>(System.IO.File.ReadAllText("Files/GameEvents.json"));
fakeLogger = A.Fake<ILogger>();
serviceProvider = new ServiceCollection() serviceProvider = new ServiceCollection()
.AddSingleton<BaseEventParser>() .AddSingleton<BaseEventParser>()
.AddTransient<IParserPatternMatcher, ParserPatternMatcher>() .AddTransient<IParserPatternMatcher, ParserPatternMatcher>()
.AddSingleton<IParserRegexFactory, ParserRegexFactory>() .AddSingleton<IParserRegexFactory, ParserRegexFactory>()
.AddSingleton(fakeLogger)
.BuildServiceProvider(); .BuildServiceProvider();
} }
@ -54,5 +60,54 @@ namespace ApplicationTests
AssertMatch(parsedEvent, e); AssertMatch(parsedEvent, e);
} }
} }
[Test]
public void TestCustomEvents()
{
var eventParser = serviceProvider.GetService<BaseEventParser>();
string eventMessage = "Hello this is my test event message";
string triggerValue = "testTrigger";
string eventType = "testType";
eventParser.RegisterCustomEvent(eventType, triggerValue, (logLine, config, generatedEvent) =>
{
generatedEvent.Message = eventMessage;
return generatedEvent;
});
var customEvent = eventParser.GenerateGameEvent($"23:14 {triggerValue}");
Assert.AreEqual(EventType.Other, customEvent.Type);
Assert.AreEqual(eventType, customEvent.Subtype);
Assert.AreEqual(eventMessage, customEvent.Message);
}
[Test]
public void TestCustomEventRegistrationArguments()
{
var eventParser = serviceProvider.GetService<BaseEventParser>();
Assert.Throws<ArgumentException>(() => eventParser.RegisterCustomEvent(null, null, null));
Assert.Throws<ArgumentException>(() => eventParser.RegisterCustomEvent("test", null, null));
Assert.Throws<ArgumentException>(() => eventParser.RegisterCustomEvent("test", "test2", null));
Assert.Throws<ArgumentException>(() =>
{
// testing duplicate registers
eventParser.RegisterCustomEvent("test", "test", (a, b, c) => new GameEvent());
eventParser.RegisterCustomEvent("test", "test", (a, b, c) => new GameEvent());
});
}
[Test]
public void TestCustomEventParsingLogsWarningOnException()
{
var eventParser = serviceProvider.GetService<BaseEventParser>();
eventParser.RegisterCustomEvent("test", "test", (a, b, c) => throw new Exception());
eventParser.GenerateGameEvent("12:12 test");
A.CallTo(() => fakeLogger.WriteWarning(A<string>.Ignored))
.MustHaveHappenedOnceExactly();
}
} }
} }

View File

@ -35,7 +35,7 @@ namespace ApplicationTests
new SharedLibraryCore.Configuration.ServerConfiguration() { IPAddress = "127.0.0.1", Port = 28960 }, new SharedLibraryCore.Configuration.ServerConfiguration() { IPAddress = "127.0.0.1", Port = 28960 },
A.Fake<ITranslationLookup>(), A.Fake<IRConConnectionFactory>()); A.Fake<ITranslationLookup>(), A.Fake<IRConConnectionFactory>());
var parser = new BaseEventParser(A.Fake<IParserRegexFactory>()); var parser = new BaseEventParser(A.Fake<IParserRegexFactory>(), A.Fake<ILogger>());
parser.Configuration.GuidNumberStyle = System.Globalization.NumberStyles.Integer; parser.Configuration.GuidNumberStyle = System.Globalization.NumberStyles.Integer;
var log = System.IO.File.ReadAllLines("Files\\T6MapRotation.log"); var log = System.IO.File.ReadAllLines("Files\\T6MapRotation.log");
@ -61,7 +61,7 @@ namespace ApplicationTests
new SharedLibraryCore.Configuration.ServerConfiguration() { IPAddress = "127.0.0.1", Port = 28960 }, new SharedLibraryCore.Configuration.ServerConfiguration() { IPAddress = "127.0.0.1", Port = 28960 },
A.Fake<ITranslationLookup>(), A.Fake<IRConConnectionFactory>()); A.Fake<ITranslationLookup>(), A.Fake<IRConConnectionFactory>());
var parser = new BaseEventParser(A.Fake<IParserRegexFactory>()); var parser = new BaseEventParser(A.Fake<IParserRegexFactory>(), A.Fake<ILogger>());
parser.Configuration.GuidNumberStyle = System.Globalization.NumberStyles.Integer; parser.Configuration.GuidNumberStyle = System.Globalization.NumberStyles.Integer;
var log = System.IO.File.ReadAllLines("Files\\T6Game.log"); var log = System.IO.File.ReadAllLines("Files\\T6Game.log");

View File

@ -56,7 +56,7 @@ namespace ApplicationTests
A.Fake<ITranslationLookup>(), A.Fake<ITranslationLookup>(),
A.Fake<IRConConnectionFactory>()); A.Fake<IRConConnectionFactory>());
var parser = new BaseEventParser(A.Fake<IParserRegexFactory>()); var parser = new BaseEventParser(A.Fake<IParserRegexFactory>(), A.Fake<ILogger>());
parser.Configuration.GuidNumberStyle = System.Globalization.NumberStyles.Integer; parser.Configuration.GuidNumberStyle = System.Globalization.NumberStyles.Integer;
var log = System.IO.File.ReadAllLines("Files\\T6GameStats.log"); var log = System.IO.File.ReadAllLines("Files\\T6GameStats.log");

View File

@ -0,0 +1,32 @@
using NUnit.Framework;
using SharedLibraryCore;
namespace ApplicationTests
{
[TestFixture]
public class UtilitiesTests
{
[Test]
public void TestCapClientNameLengthReachesMax()
{
string originalName = "SomeVeryLongName";
string expectedName = "SomeVeryLong...";
int maxLength = originalName.Length - 1;
string cappedName = originalName.CapClientName(maxLength);
Assert.AreEqual(expectedName, cappedName);
}
[Test]
public void TestCapClientNameRetainsOriginal()
{
string originalName = "Short";
int maxLength = originalName.Length;
string cappedName = originalName.CapClientName(maxLength);
Assert.AreEqual(originalName, cappedName);
}
}
}