update live radar plugin to IPluginV2

This commit is contained in:
RaidMax 2023-02-11 20:46:08 -06:00
parent 2688790736
commit ba9e393363
8 changed files with 586 additions and 583 deletions

View File

@ -1,10 +1,10 @@
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using System.Collections.Generic; using System.Collections.Generic;
namespace LiveRadar.Configuration namespace IW4MAdmin.Plugins.LiveRadar.Configuration;
public class LiveRadarConfiguration : IBaseConfiguration
{ {
class LiveRadarConfiguration : IBaseConfiguration
{
public List<MapInfo> Maps { get; set; } public List<MapInfo> Maps { get; set; }
public IBaseConfiguration Generate() public IBaseConfiguration Generate()
@ -387,5 +387,4 @@ namespace LiveRadar.Configuration
} }
public string Name() => "LiveRadar"; public string Name() => "LiveRadar";
}
} }

View File

@ -1,26 +1,24 @@
using LiveRadar.Configuration; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using SharedLibraryCore; using SharedLibraryCore;
using SharedLibraryCore.Dtos; using SharedLibraryCore.Dtos;
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using IW4MAdmin.Plugins.LiveRadar.Configuration;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
namespace LiveRadar.Web.Controllers namespace IW4MAdmin.Plugins.LiveRadar.Web.Controllers
{ {
public class RadarController : BaseController public class RadarController : BaseController
{ {
private readonly IManager _manager; private readonly IManager _manager;
private static LiveRadarConfiguration _config; private readonly LiveRadarConfiguration _config;
private readonly IConfigurationHandler<LiveRadarConfiguration> _configurationHandler;
public RadarController(IManager manager, IConfigurationHandlerFactory configurationHandlerFactory) : public RadarController(IManager manager, LiveRadarConfiguration config) :
base(manager) base(manager)
{ {
_manager = manager; _manager = manager;
_configurationHandler = _config = config;
configurationHandlerFactory.GetConfigurationHandler<LiveRadarConfiguration>("LiveRadarConfiguration");
} }
[HttpGet] [HttpGet]
@ -32,8 +30,8 @@ namespace LiveRadar.Web.Controllers
.Select(server => new ServerInfo .Select(server => new ServerInfo
{ {
Name = server.Hostname, Name = server.Hostname,
IPAddress = server.IP, IPAddress = server.ListenAddress,
Port = server.Port Port = server.ListenPort
}); });
ViewBag.Title = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_RADAR_TITLE"]; ViewBag.Title = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_RADAR_TITLE"];
@ -56,12 +54,6 @@ namespace LiveRadar.Web.Controllers
return NotFound(); return NotFound();
} }
if (_config == null)
{
await _configurationHandler.BuildAsync();
_config = _configurationHandler.Configuration() ?? new LiveRadarConfiguration();
}
var map = _config.Maps.FirstOrDefault(map => map.Name == server.CurrentMap.Name); var map = _config.Maps.FirstOrDefault(map => map.Name == server.CurrentMap.Name);
if (map == null) if (map == null)

View File

@ -0,0 +1,38 @@
using SharedLibraryCore;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Interfaces;
using System.Collections.Generic;
using SharedLibraryCore.Events.Game;
using EventGeneratorCallback = System.ValueTuple<string, string,
System.Func<string, SharedLibraryCore.Interfaces.IEventParserConfiguration,
SharedLibraryCore.GameEvent,
SharedLibraryCore.GameEvent>>;
namespace IW4MAdmin.Plugins.LiveRadar.Events;
public class Script : IRegisterEvent
{
private const string EventLiveRadar = "LiveRadar";
private EventGeneratorCallback LiveRadar()
{
return (EventLiveRadar, EventLiveRadar, (eventLine, _, _) =>
{
var radarEvent = new LiveRadarEvent
{
Type = GameEvent.EventType.Other,
Subtype = EventLiveRadar,
Origin = new EFClient { NetworkId = 0 },
ScriptData = eventLine
};
return radarEvent;
}
);
}
public IEnumerable<EventGeneratorCallback> Events => new[] { LiveRadar() };
}
public class LiveRadarEvent : GameScriptEvent
{
}

View File

@ -1,33 +0,0 @@
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 LiveRadar.Events
{
public class Script : IRegisterEvent
{
private const string EVENT_LIVERADAR = "LiveRadar";
private EventGeneratorCallback LiveRadar()
{
return (EVENT_LIVERADAR, EVENT_LIVERADAR, (string eventLine, IEventParserConfiguration config, GameEvent autoEvent) =>
{
string[] lineSplit = eventLine.Split(";");
autoEvent.Type = GameEvent.EventType.Other;
autoEvent.Subtype = EVENT_LIVERADAR;
autoEvent.Origin = new EFClient() { NetworkId = 0 };
autoEvent.Extra = lineSplit[1]; // guid
return autoEvent;
}
);
}
public IEnumerable<EventGeneratorCallback> Events => new[] { LiveRadar() };
}
}

View File

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

View File

@ -1,11 +1,7 @@
using System; namespace IW4MAdmin.Plugins.LiveRadar;
using System.Collections.Generic;
using System.Text;
namespace LiveRadar public class MapInfo
{ {
public class MapInfo
{
public string Name { get; set; } public string Name { get; set; }
public string Alias { get; set; } public string Alias { get; set; }
// distance from the edge of the minimap image // distance from the edge of the minimap image
@ -27,5 +23,4 @@ namespace LiveRadar
public int Width => MaxLeft - MaxRight; public int Width => MaxLeft - MaxRight;
public int Height => MaxTop - MaxBottom; public int Height => MaxTop - MaxBottom;
}
} }

View File

@ -1,85 +1,78 @@
using LiveRadar.Configuration; using SharedLibraryCore;
using SharedLibraryCore;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Data.Models;
using IW4MAdmin.Plugins.LiveRadar.Configuration;
using IW4MAdmin.Plugins.LiveRadar.Events;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SharedLibraryCore.Configuration; using SharedLibraryCore.Configuration;
using SharedLibraryCore.Events.Game;
using SharedLibraryCore.Events.Server;
using SharedLibraryCore.Interfaces; using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Interfaces.Events;
using ILogger = Microsoft.Extensions.Logging.ILogger; using ILogger = Microsoft.Extensions.Logging.ILogger;
namespace LiveRadar namespace IW4MAdmin.Plugins.LiveRadar;
public class Plugin : IPluginV2
{ {
public class Plugin : IPlugin
{
public string Name => "Live Radar"; public string Name => "Live Radar";
public float Version => (float)Utilities.GetVersionAsDouble(); public string Version => Utilities.GetVersionAsString();
public string Author => "RaidMax"; public string Author => "RaidMax";
private readonly IConfigurationHandler<LiveRadarConfiguration> _configurationHandler; private bool _addedPage;
private readonly Dictionary<string, long> _botGuidLookups; private readonly Dictionary<string, long> _botGuidLookups;
private bool addedPage; private readonly object _lockObject = new();
private readonly object lockObject = new object();
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ApplicationConfiguration _appConfig; private readonly ApplicationConfiguration _appConfig;
public Plugin(ILogger<Plugin> logger, IConfigurationHandlerFactory configurationHandlerFactory, ApplicationConfiguration appConfig) public static void RegisterDependencies(IServiceCollection serviceCollection)
{
serviceCollection.AddConfiguration<LiveRadarConfiguration>();
}
public Plugin(ILogger<Plugin> logger, ApplicationConfiguration appConfig)
{ {
_configurationHandler = configurationHandlerFactory.GetConfigurationHandler<LiveRadarConfiguration>("LiveRadarConfiguration");
_botGuidLookups = new Dictionary<string, long>(); _botGuidLookups = new Dictionary<string, long>();
_logger = logger; _logger = logger;
_appConfig = appConfig; _appConfig = appConfig;
IGameServerEventSubscriptions.MonitoringStarted += OnMonitoringStarted;
IGameEventSubscriptions.ClientEnteredMatch += OnClientEnteredMatch;
IGameEventSubscriptions.ScriptEventTriggered += OnScriptEvent;
} }
public Task OnEventAsync(GameEvent E, Server S) private Task OnScriptEvent(GameScriptEvent scriptEvent, CancellationToken token)
{ {
// if it's an IW4 game, with custom callbacks, we want to if (scriptEvent is not LiveRadarEvent radarEvent)
// enable the live radar page
lock (lockObject)
{
if (E.Type == GameEvent.EventType.Start &&
S.GameName == Server.Game.IW4 &&
S.CustomCallback &&
!addedPage)
{
E.Owner.Manager.GetPageList().Pages.Add(Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_RADAR_TITLE"], "/Radar");
addedPage = true;
}
}
if (E.Type == GameEvent.EventType.PreConnect && E.Origin.IsBot)
{
string botKey = $"BotGuid_{E.Extra}";
lock (lockObject)
{
if (!_botGuidLookups.ContainsKey(botKey))
{
_botGuidLookups.Add(botKey, E.Origin.NetworkId);
}
}
}
if (E.Type == GameEvent.EventType.Other && E.Subtype == "LiveRadar")
{
try
{
if (((string) E.Extra).IsBotGuid() && _appConfig.IgnoreBots)
{ {
return Task.CompletedTask; return Task.CompletedTask;
} }
string botKey = $"BotGuid_{E.Extra}"; try
{
var originalBotGuid = radarEvent.ScriptData.Split(";")[1];
if (originalBotGuid.IsBotGuid() && _appConfig.IgnoreBots)
{
return Task.CompletedTask;
}
var botKey = $"BotGuid_{originalBotGuid}";
long generatedBotGuid; long generatedBotGuid;
lock (lockObject) lock (_lockObject)
{ {
var hasBotKey = _botGuidLookups.ContainsKey(botKey); var hasBotKey = _botGuidLookups.ContainsKey(botKey);
if (!hasBotKey && ((string)E.Extra).IsBotGuid()) if (!hasBotKey && originalBotGuid.IsBotGuid())
{ {
// edge case where the bot guid has not been registered yet // edge case where the bot guid has not been registered yet
return Task.CompletedTask; return Task.CompletedTask;
@ -87,11 +80,12 @@ namespace LiveRadar
generatedBotGuid = hasBotKey generatedBotGuid = hasBotKey
? _botGuidLookups[botKey] ? _botGuidLookups[botKey]
: (E.Extra.ToString() ?? "0").ConvertGuidToLong(NumberStyles.HexNumber); : (originalBotGuid ?? "0").ConvertGuidToLong(NumberStyles.HexNumber);
} }
var radarUpdate = RadarEvent.Parse(E.Data, generatedBotGuid); var radarUpdate = RadarEvent.Parse(scriptEvent.ScriptData, generatedBotGuid);
var client = S.Manager.GetActiveClients().FirstOrDefault(_client => _client.NetworkId == radarUpdate.Guid); var client =
radarEvent.Owner.ConnectedClients.FirstOrDefault(client => client.NetworkId == radarUpdate.Guid);
if (client != null) if (client != null)
{ {
@ -102,31 +96,50 @@ namespace LiveRadar
catch (Exception e) catch (Exception e)
{ {
_logger.LogError(e, "Could not parse live radar output: {data}", e.Data); _logger.LogError(e, "Could not parse live radar output: {Data}", e.Data);
}
return Task.CompletedTask;
}
private Task OnClientEnteredMatch(ClientEnterMatchEvent clientEvent, CancellationToken token)
{
if (!clientEvent.Client.IsBot)
{
return Task.CompletedTask;
}
var botKey = $"BotGuid_{clientEvent.ClientNetworkId}";
lock (_lockObject)
{
if (!_botGuidLookups.ContainsKey(botKey))
{
_botGuidLookups.Add(botKey, clientEvent.Client.NetworkId);
} }
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
public async Task OnLoadAsync(IManager manager) private Task OnMonitoringStarted(MonitorStartEvent monitorEvent, CancellationToken token)
{ {
await _configurationHandler.BuildAsync(); lock (_lockObject)
if (_configurationHandler.Configuration() == null)
{ {
_configurationHandler.Set((LiveRadarConfiguration)new LiveRadarConfiguration().Generate()); // if it's an IW4 game, with custom callbacks, we want to
await _configurationHandler.Save(); // enable the live radar page
} var shouldRegisterPage = monitorEvent.Server.GameCode != Reference.Game.IW4 ||
} !monitorEvent.Server.IsLegacyGameIntegrationEnabled ||
_addedPage;
public Task OnTickAsync(Server S) if (shouldRegisterPage)
{ {
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task OnUnloadAsync() (monitorEvent.Source as IManager)?.GetPageList().Pages
{ .Add(Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_RADAR_TITLE"], "/Radar");
return Task.CompletedTask; _addedPage = true;
} }
return Task.CompletedTask;
} }
} }

View File

@ -5,10 +5,10 @@ using System.Linq;
// ReSharper disable CompareOfFloatsByEqualityOperator // ReSharper disable CompareOfFloatsByEqualityOperator
#pragma warning disable CS0659 #pragma warning disable CS0659
namespace LiveRadar namespace IW4MAdmin.Plugins.LiveRadar;
public class RadarEvent
{ {
public class RadarEvent
{
public string Name { get; set; } public string Name { get; set; }
public long Guid { get; set; } public long Guid { get; set; }
public Vector3 Location { get; set; } public Vector3 Location { get; set; }
@ -60,5 +60,4 @@ namespace LiveRadar
return parsedEvent; return parsedEvent;
} }
}
} }