Compare commits
180 Commits
2.0
...
2.3-prerel
Author | SHA1 | Date | |
---|---|---|---|
02622ea7de | |||
03ae3b5822 | |||
0711249a46 | |||
18f4ffa9ff | |||
934fead5c2 | |||
02cad10d77 | |||
b134cd4728 | |||
b9c4a1b5f6 | |||
f0fd4c66e9 | |||
52fe8fc847 | |||
9f8c35dbed | |||
9d9be7f8af | |||
dd82a5e3fa | |||
8667532d24 | |||
863ba8b096 | |||
8ab89e113d | |||
00634780d4 | |||
6f80f1edbb | |||
9393b35c39 | |||
37d3f4f90d | |||
8521df85f5 | |||
7b8126d57e | |||
1e2e2218e3 | |||
11e3235d5d | |||
cae6d8389e | |||
1056c7c335 | |||
95e4ee672e | |||
bf0a0befc6 | |||
53c3ff6ce3 | |||
c8ec0eefa9 | |||
82bae772f0 | |||
af3aea77bc | |||
b3e5f468a1 | |||
c21bf2ebf1 | |||
d318a57830 | |||
61f1436faf | |||
0c527a5f65 | |||
1457b843e2 | |||
de69bed792 | |||
4b1f44cc2a | |||
74cdf8e885 | |||
5d41059641 | |||
2e6889d9bb | |||
9c4d23f0b4 | |||
b4e3e8526a | |||
e3944fb8c2 | |||
40f1697c97 | |||
2bbf2988da | |||
5e36bf4316 | |||
a362caebac | |||
2260d8974d | |||
5e04274da6 | |||
6d2e6aee4f | |||
9e74c42246 | |||
dea5b3f954 | |||
7c6419a16a | |||
0194196a33 | |||
044991272f | |||
f3290cf066 | |||
29eedea093 | |||
ce02f5dd68 | |||
e6bfa408f8 | |||
0a1dc46760 | |||
97ba6aae2e | |||
a456fab0e5 | |||
3e5282df87 | |||
59e0072744 | |||
f1dd4f7c7f | |||
760d3026ce | |||
07df6dbf79 | |||
ca535019c6 | |||
e6154822f6 | |||
7a6dccc26a | |||
08c883e0ff | |||
aaf9eb09b6 | |||
7b75c35c9b | |||
07ec5cf52f | |||
cf5ee8765d | |||
9494a17997 | |||
5f4171ccf4 | |||
a10746d5ff | |||
8dca05a442 | |||
8aa0d204f4 | |||
12cf2e8247 | |||
b77bdbe793 | |||
4522992c0e | |||
9d6cbee69c | |||
abf0609e2e | |||
5ac8a55c72 | |||
9bdd7d1b8a | |||
ed83c4c011 | |||
d9d548ea18 | |||
1779bf821d | |||
d50e6c8030 | |||
a58726d872 | |||
dded60a6ef | |||
305817d00c | |||
65cf3566db | |||
e91d076b41 | |||
b5e9519f0c | |||
7caee55a7e | |||
b289917319 | |||
c8366a22e5 | |||
de902a58ac | |||
c7547f1ad5 | |||
9d946d1bad | |||
f4ac815d07 | |||
7fa0b52543 | |||
d45729d7e1 | |||
5d93e7ac57 | |||
0f9d2e92e1 | |||
4a46abc46d | |||
7c708f06f3 | |||
98adfb12d2 | |||
a786541484 | |||
b9086fd145 | |||
3d8108f339 | |||
39596db56e | |||
ba5b1e19a6 | |||
385879618d | |||
0c90d02e44 | |||
cfbacabb4a | |||
672d45df7c | |||
20d4ab27d3 | |||
e77ef69ee8 | |||
cc7628d058 | |||
46bdc2ac33 | |||
bbefd53db4 | |||
56cb8c50e7 | |||
0538d9f479 | |||
1343d4959e | |||
ac64d8d3c1 | |||
b5939bbdaf | |||
a0fafe5797 | |||
bbade07646 | |||
3c0e101f14 | |||
d0be08629d | |||
9d00d5a16a | |||
396e5c9215 | |||
4ec16d3aa2 | |||
f40bcce44f | |||
6071ad8653 | |||
16d7ccd590 | |||
87541c4a5a | |||
af6361144e | |||
454238a192 | |||
e7c7145da1 | |||
5be6b75ccf | |||
e60f612f95 | |||
ba023ceeb5 | |||
e3dba96d72 | |||
6d0f859a93 | |||
696e2d12c9 | |||
bf68e5672f | |||
2204686b08 | |||
897ec0d0c1 | |||
d9a601328c | |||
36d493f05b | |||
be68335f70 | |||
4d585e6ab2 | |||
4006c09045 | |||
699c19cd4b | |||
6e5501b32d | |||
e964013700 | |||
9ff7f39e8d | |||
a54ea3913d | |||
e8dff01c41 | |||
3092a529e9 | |||
f442f251f6 | |||
3a463be7f8 | |||
35e7f57156 | |||
8071fb37bc | |||
bb90a807b7 | |||
2c2c442ba7 | |||
b6c979beba | |||
99390f1f35 | |||
ece519251a | |||
0e3d280595 | |||
5dfaa4ebd6 | |||
02ef5a0bf8 |
14
.gitignore
vendored
14
.gitignore
vendored
@ -220,7 +220,17 @@ Thumbs.db
|
||||
DEPLOY
|
||||
global.min.css
|
||||
global.min.js
|
||||
bootstrap-custom.css
|
||||
bootstrap-custom.min.css
|
||||
**/Master/static
|
||||
**/Master/dev_env
|
||||
**/Master/dev_env
|
||||
/WebfrontCore/Views/Plugins/*
|
||||
/WebfrontCore/wwwroot/**/dds
|
||||
|
||||
/DiscordWebhook/env
|
||||
/DiscordWebhook/config.dev.json
|
||||
/GameLogServer/env
|
||||
launchSettings.json
|
||||
/VpnDetectionPrivate.js
|
||||
/Plugins/ScriptPlugins/VpnDetectionPrivate.js
|
||||
**/Master/env_master
|
||||
/GameLogServer/log_env
|
||||
|
@ -1,75 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Dtos;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
|
||||
namespace IW4MAdmin.Application.API
|
||||
{
|
||||
class EventApi : IEventApi
|
||||
{
|
||||
Queue<EventInfo> Events = new Queue<EventInfo>();
|
||||
DateTime LastFlagEvent;
|
||||
static string[] FlaggedMessageContains =
|
||||
{
|
||||
" wh ",
|
||||
"hax",
|
||||
"cheat",
|
||||
" hack ",
|
||||
"aim",
|
||||
"wall",
|
||||
"cheto",
|
||||
"hak",
|
||||
"bot"
|
||||
};
|
||||
int FlaggedMessageCount;
|
||||
|
||||
public Queue<EventInfo> GetEvents() => Events;
|
||||
|
||||
public void OnServerEvent(object sender, GameEvent E)
|
||||
{
|
||||
if (E.Type == GameEvent.EventType.Say && E.Origin.Level < Player.Permission.Trusted)
|
||||
{
|
||||
bool flaggedMessage = false;
|
||||
foreach (string msg in FlaggedMessageContains)
|
||||
flaggedMessage = flaggedMessage ? flaggedMessage : E.Data.ToLower().Contains(msg);
|
||||
|
||||
if (flaggedMessage)
|
||||
FlaggedMessageCount++;
|
||||
|
||||
if (FlaggedMessageCount > 3)
|
||||
{
|
||||
if (Events.Count > 20)
|
||||
Events.Dequeue();
|
||||
|
||||
FlaggedMessageCount = 0;
|
||||
|
||||
E.Owner.Broadcast("If you suspect someone of ^5CHEATING ^7use the ^5!report ^7command").Wait();
|
||||
Events.Enqueue(new EventInfo(
|
||||
EventInfo.EventType.ALERT,
|
||||
EventInfo.EventVersion.IW4MAdmin,
|
||||
"Chat indicates there may be a cheater",
|
||||
"Alert",
|
||||
E.Owner.Hostname, ""));
|
||||
}
|
||||
|
||||
if ((DateTime.UtcNow - LastFlagEvent).Minutes >= 3)
|
||||
{
|
||||
FlaggedMessageCount = 0;
|
||||
LastFlagEvent = DateTime.Now;
|
||||
}
|
||||
}
|
||||
|
||||
if (E.Type == GameEvent.EventType.Report)
|
||||
{
|
||||
Events.Enqueue(new EventInfo(
|
||||
EventInfo.EventType.ALERT,
|
||||
EventInfo.EventVersion.IW4MAdmin,
|
||||
$"**{E.Origin.Name}** has reported **{E.Target.Name}** for: {E.Data.Trim()}",
|
||||
E.Target.Name, E.Origin.Name, ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
12
Application/API/GameLogServer/IGameLogServer.cs
Normal file
12
Application/API/GameLogServer/IGameLogServer.cs
Normal file
@ -0,0 +1,12 @@
|
||||
using System.Threading.Tasks;
|
||||
using RestEase;
|
||||
|
||||
namespace IW4MAdmin.Application.API.GameLogServer
|
||||
{
|
||||
[Header("User-Agent", "IW4MAdmin-RestEase")]
|
||||
public interface IGameLogServer
|
||||
{
|
||||
[Get("log/{path}")]
|
||||
Task<LogInfo> Log([Path] string path);
|
||||
}
|
||||
}
|
17
Application/API/GameLogServer/LogInfo.cs
Normal file
17
Application/API/GameLogServer/LogInfo.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace IW4MAdmin.Application.API.GameLogServer
|
||||
{
|
||||
public class LogInfo
|
||||
{
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
[JsonProperty("length")]
|
||||
public int Length { get; set; }
|
||||
[JsonProperty("data")]
|
||||
public string Data { get; set; }
|
||||
}
|
||||
}
|
@ -8,9 +8,13 @@ namespace IW4MAdmin.Application.API.Master
|
||||
public class ApiServer
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int Id { get; set; }
|
||||
public long Id { get; set; }
|
||||
[JsonProperty("ip")]
|
||||
public string IPAddress { get; set; }
|
||||
[JsonProperty("port")]
|
||||
public short Port { get; set; }
|
||||
[JsonProperty("version")]
|
||||
public string Version { get; set; }
|
||||
[JsonProperty("gametype")]
|
||||
public string Gametype { get; set; }
|
||||
[JsonProperty("map")]
|
||||
|
@ -2,15 +2,21 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using RestEase;
|
||||
using SharedLibraryCore;
|
||||
|
||||
namespace IW4MAdmin.Application.API.Master
|
||||
{
|
||||
public class HeartbeatState
|
||||
{
|
||||
public bool Connected { get; set; }
|
||||
public CancellationToken Token { get; set; }
|
||||
}
|
||||
|
||||
public class Heartbeat
|
||||
{
|
||||
|
||||
public static async Task Send(ApplicationManager mgr, bool firstHeartbeat = false)
|
||||
{
|
||||
var api = Endpoint.Get();
|
||||
@ -35,12 +41,14 @@ namespace IW4MAdmin.Application.API.Master
|
||||
{
|
||||
ClientNum = s.ClientNum,
|
||||
Game = s.GameName.ToString(),
|
||||
Version = s.Version,
|
||||
Gametype = s.Gametype,
|
||||
Hostname = s.Hostname,
|
||||
Map = s.CurrentMap.Name,
|
||||
MaxClientNum = s.MaxClients,
|
||||
Id = s.GetHashCode(),
|
||||
Port = (short)s.GetPort()
|
||||
Id = s.EndPoint,
|
||||
Port = (short)s.GetPort(),
|
||||
IPAddress = s.IP
|
||||
}).ToList()
|
||||
};
|
||||
|
||||
|
@ -8,7 +8,7 @@ using RestEase;
|
||||
namespace IW4MAdmin.Application.API.Master
|
||||
{
|
||||
public class AuthenticationId
|
||||
{
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public string Id { get; set; }
|
||||
}
|
||||
@ -36,7 +36,7 @@ namespace IW4MAdmin.Application.API.Master
|
||||
public class Endpoint
|
||||
{
|
||||
#if !DEBUG
|
||||
private static IMasterApi api = RestClient.For<IMasterApi>("http://api.raidmax.org:5000");
|
||||
private static readonly IMasterApi api = RestClient.For<IMasterApi>("http://api.raidmax.org:5000");
|
||||
#else
|
||||
private static IMasterApi api = RestClient.For<IMasterApi>("http://127.0.0.1");
|
||||
#endif
|
||||
@ -60,5 +60,11 @@ namespace IW4MAdmin.Application.API.Master
|
||||
|
||||
[Get("version")]
|
||||
Task<VersionInfo> GetVersion();
|
||||
|
||||
[Get("localization")]
|
||||
Task<List<SharedLibraryCore.Localization.Layout>> GetLocalization();
|
||||
|
||||
[Get("localization/{languageTag}")]
|
||||
Task<SharedLibraryCore.Localization.Layout> GetLocalization([Path("languageTag")] string languageTag);
|
||||
}
|
||||
}
|
||||
|
@ -2,15 +2,16 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<RuntimeFrameworkVersion>2.2.2</RuntimeFrameworkVersion>
|
||||
<MvcRazorExcludeRefAssembliesFromPublish>false</MvcRazorExcludeRefAssembliesFromPublish>
|
||||
<PackageId>RaidMax.IW4MAdmin.Application</PackageId>
|
||||
<Version>2.1.0</Version>
|
||||
<Version>2.2.6.5</Version>
|
||||
<Authors>RaidMax</Authors>
|
||||
<Company>Forever None</Company>
|
||||
<Product>IW4MAdmin</Product>
|
||||
<Description>IW4MAdmin is a complete server administration tool for IW4x and most Call of Duty® dedicated server</Description>
|
||||
<Copyright>2018</Copyright>
|
||||
<Description>IW4MAdmin is a complete server administration tool for IW4x and most Call of Duty® dedicated servers</Description>
|
||||
<Copyright>2019</Copyright>
|
||||
<PackageLicenseUrl>https://github.com/RaidMax/IW4M-Admin/blob/master/LICENSE</PackageLicenseUrl>
|
||||
<PackageProjectUrl>https://raidmax.org/IW4MAdmin</PackageProjectUrl>
|
||||
<RepositoryUrl>https://github.com/RaidMax/IW4M-Admin</RepositoryUrl>
|
||||
@ -19,13 +20,21 @@
|
||||
<AssemblyName>IW4MAdmin</AssemblyName>
|
||||
<Configurations>Debug;Release;Prerelease</Configurations>
|
||||
<Win32Resource />
|
||||
<RootNamespace>IW4MAdmin.Application</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="RestEase" Version="1.4.5" />
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.4.0" />
|
||||
<PackageReference Include="RestEase" Version="1.4.7" />
|
||||
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.5.1" />
|
||||
</ItemGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<ServerGarbageCollection>true</ServerGarbageCollection>
|
||||
<TieredCompilation>true</TieredCompilation>
|
||||
<AssemblyVersion>2.2.6.5</AssemblyVersion>
|
||||
<FileVersion>2.2.6.5</FileVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SharedLibraryCore\SharedLibraryCore.csproj">
|
||||
<Private>true</Private>
|
||||
@ -36,40 +45,28 @@
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\IW4MAdmin.en-US.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>IW4MAdmin.en-US.resx</DependentUpon>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Update="Properties\IW4MAdmin.en-US.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>IW4MAdmin.en-US.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="DefaultSettings.json">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="Localization\IW4MAdmin.en-US.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Update="Microsoft.NETCore.App" Version="2.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PreBuild" BeforeTargets="PreBuildEvent">
|
||||
<Exec Command="call $(ProjectDir)BuildScripts\PreBuild.bat $(SolutionDir) $(ProjectDir) $(TargetDir) $(OutDir)" />
|
||||
<Exec Command="call $(ProjectDir)BuildScripts\PreBuild.bat $(ProjectDir)..\ $(ProjectDir) $(TargetDir) $(OutDir)" />
|
||||
</Target>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
<Exec Command="call $(ProjectDir)BuildScripts\PostBuild.bat $(SolutionDir) $(ProjectDir) $(TargetDir) $(OutDir)" />
|
||||
<GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
|
||||
<Output TaskParameter="Assemblies" ItemName="CurrentAssembly" />
|
||||
</GetAssemblyIdentity>
|
||||
<Exec Command="call $(ProjectDir)BuildScripts\PostBuild.bat $(ProjectDir)..\ $(ProjectDir) $(TargetDir) $(OutDir) %(CurrentAssembly.Version)" />
|
||||
</Target>
|
||||
|
||||
<Target Name="PostPublish" AfterTargets="Publish">
|
||||
<Exec Command="call $(ProjectDir)BuildScripts\PostPublish.bat $(SolutionDir) $(ProjectDir) $(TargetDir) $(OutDir)" />
|
||||
<Exec Command="call $(ProjectDir)BuildScripts\PostPublish.bat $(ProjectDir)..\ $(ProjectDir) $(TargetDir) $(ConfigurationName)" />
|
||||
</Target>
|
||||
|
||||
</Project>
|
||||
|
777
Application/ApplicationManager.cs
Normal file
777
Application/ApplicationManager.cs
Normal file
@ -0,0 +1,777 @@
|
||||
using IW4MAdmin.Application.API.Master;
|
||||
using IW4MAdmin.Application.EventParsers;
|
||||
using IW4MAdmin.Application.Misc;
|
||||
using IW4MAdmin.Application.RconParsers;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Commands;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using SharedLibraryCore.Database;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Dtos;
|
||||
using SharedLibraryCore.Events;
|
||||
using SharedLibraryCore.Exceptions;
|
||||
using SharedLibraryCore.Helpers;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
using SharedLibraryCore.Services;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
public class ApplicationManager : IManager
|
||||
{
|
||||
private List<Server> _servers;
|
||||
public List<Server> Servers => _servers.OrderByDescending(s => s.ClientNum).ToList();
|
||||
public Dictionary<int, EFClient> PrivilegedClients { get; set; }
|
||||
public ILogger Logger => GetLogger(0);
|
||||
public bool Running { get; private set; }
|
||||
public bool IsInitialized { get; private set; }
|
||||
// define what the delagate function looks like
|
||||
public delegate void OnServerEventEventHandler(object sender, GameEventArgs e);
|
||||
// expose the event handler so we can execute the events
|
||||
public OnServerEventEventHandler OnServerEvent { get; set; }
|
||||
public DateTime StartTime { get; private set; }
|
||||
public string Version => Assembly.GetEntryAssembly().GetName().Version.ToString();
|
||||
|
||||
public IList<IRConParser> AdditionalRConParsers { get; }
|
||||
public IList<IEventParser> AdditionalEventParsers { get; }
|
||||
public ITokenAuthentication TokenAuthenticator => Authenticator;
|
||||
public ITokenAuthentication Authenticator => _authenticator;
|
||||
public string ExternalIPAddress { get; private set; }
|
||||
|
||||
static ApplicationManager Instance;
|
||||
readonly List<AsyncStatus> TaskStatuses;
|
||||
List<Command> Commands;
|
||||
readonly List<MessageToken> MessageTokens;
|
||||
ClientService ClientSvc;
|
||||
readonly AliasService AliasSvc;
|
||||
readonly PenaltyService PenaltySvc;
|
||||
public BaseConfigurationHandler<ApplicationConfiguration> ConfigHandler;
|
||||
GameEventHandler Handler;
|
||||
ManualResetEventSlim OnQuit;
|
||||
readonly IPageList PageList;
|
||||
readonly SemaphoreSlim ProcessingEvent = new SemaphoreSlim(1, 1);
|
||||
readonly Dictionary<long, ILogger> Loggers = new Dictionary<long, ILogger>();
|
||||
readonly ITokenAuthentication _authenticator;
|
||||
private readonly MetaService _metaService;
|
||||
private readonly TimeSpan _throttleTimeout = new TimeSpan(0, 1, 0);
|
||||
|
||||
private ApplicationManager()
|
||||
{
|
||||
_servers = new List<Server>();
|
||||
Commands = new List<Command>();
|
||||
TaskStatuses = new List<AsyncStatus>();
|
||||
MessageTokens = new List<MessageToken>();
|
||||
ClientSvc = new ClientService();
|
||||
AliasSvc = new AliasService();
|
||||
PenaltySvc = new PenaltyService();
|
||||
ConfigHandler = new BaseConfigurationHandler<ApplicationConfiguration>("IW4MAdminSettings");
|
||||
StartTime = DateTime.UtcNow;
|
||||
OnQuit = new ManualResetEventSlim();
|
||||
PageList = new PageList();
|
||||
AdditionalEventParsers = new List<IEventParser>();
|
||||
AdditionalRConParsers = new List<IRConParser>();
|
||||
OnServerEvent += OnGameEvent;
|
||||
OnServerEvent += EventApi.OnGameEvent;
|
||||
_authenticator = new TokenAuthentication();
|
||||
_metaService = new MetaService();
|
||||
}
|
||||
|
||||
private async void OnGameEvent(object sender, GameEventArgs args)
|
||||
{
|
||||
#if DEBUG == true
|
||||
Logger.WriteDebug($"Entering event process for {args.Event.Id}");
|
||||
#endif
|
||||
|
||||
var newEvent = args.Event;
|
||||
|
||||
// the event has failed already
|
||||
if (newEvent.Failed)
|
||||
{
|
||||
goto skip;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await newEvent.Owner.ExecuteEvent(newEvent);
|
||||
|
||||
// save the event info to the database
|
||||
var changeHistorySvc = new ChangeHistoryService();
|
||||
await changeHistorySvc.Add(args.Event);
|
||||
|
||||
#if DEBUG
|
||||
Logger.WriteDebug($"Processed event with id {newEvent.Id}");
|
||||
#endif
|
||||
}
|
||||
|
||||
// this happens if a plugin requires login
|
||||
catch (AuthorizationException ex)
|
||||
{
|
||||
newEvent.FailReason = GameEvent.EventFailReason.Permission;
|
||||
newEvent.Origin.Tell($"{Utilities.CurrentLocalization.LocalizationIndex["COMMAND_NOTAUTHORIZED"]} - {ex.Message}");
|
||||
}
|
||||
|
||||
catch (NetworkException ex)
|
||||
{
|
||||
newEvent.FailReason = GameEvent.EventFailReason.Exception;
|
||||
Logger.WriteError(ex.Message);
|
||||
Logger.WriteDebug(ex.GetExceptionInfo());
|
||||
}
|
||||
|
||||
catch (ServerException ex)
|
||||
{
|
||||
newEvent.FailReason = GameEvent.EventFailReason.Exception;
|
||||
Logger.WriteWarning(ex.Message);
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
newEvent.FailReason = GameEvent.EventFailReason.Exception;
|
||||
Logger.WriteError(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_EXCEPTION"].FormatExt(newEvent.Owner));
|
||||
Logger.WriteDebug(ex.GetExceptionInfo());
|
||||
}
|
||||
|
||||
skip:
|
||||
|
||||
// tell anyone waiting for the output that we're done
|
||||
newEvent.OnProcessed.Set();
|
||||
}
|
||||
|
||||
public IList<Server> GetServers()
|
||||
{
|
||||
return Servers;
|
||||
}
|
||||
|
||||
public IList<Command> GetCommands()
|
||||
{
|
||||
return Commands;
|
||||
}
|
||||
|
||||
public static ApplicationManager GetInstance()
|
||||
{
|
||||
return Instance ?? (Instance = new ApplicationManager());
|
||||
}
|
||||
|
||||
public async Task UpdateServerStates(CancellationToken token)
|
||||
{
|
||||
// store the server hash code and task for it
|
||||
var runningUpdateTasks = new Dictionary<long, Task>();
|
||||
|
||||
while (Running)
|
||||
{
|
||||
// select the server ids that have completed the update task
|
||||
var serverTasksToRemove = runningUpdateTasks
|
||||
.Where(ut => ut.Value.Status == TaskStatus.RanToCompletion ||
|
||||
ut.Value.Status == TaskStatus.Canceled ||
|
||||
ut.Value.Status == TaskStatus.Faulted)
|
||||
.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 completd
|
||||
foreach (long serverId in serverTasksToRemove)
|
||||
{
|
||||
runningUpdateTasks.Remove(serverId);
|
||||
}
|
||||
|
||||
// select the servers where the tasks have completed
|
||||
var serverIds = Servers.Select(s => s.EndPoint).Except(runningUpdateTasks.Select(r => r.Key)).ToList();
|
||||
foreach (var server in Servers.Where(s => serverIds.Contains(s.EndPoint)))
|
||||
{
|
||||
runningUpdateTasks.Add(server.EndPoint, Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await server.ProcessUpdatesAsync(token);
|
||||
if (server.Throttled)
|
||||
{
|
||||
await Task.Delay((int)_throttleTimeout.TotalMilliseconds);
|
||||
}
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.WriteWarning($"Failed to update status for {server}");
|
||||
Logger.WriteDebug(e.GetExceptionInfo());
|
||||
}
|
||||
|
||||
finally
|
||||
{
|
||||
server.IsInitialized = true;
|
||||
}
|
||||
}));
|
||||
}
|
||||
#if DEBUG
|
||||
Logger.WriteDebug($"{runningUpdateTasks.Count} servers queued for stats updates");
|
||||
ThreadPool.GetMaxThreads(out int workerThreads, out int n);
|
||||
ThreadPool.GetAvailableThreads(out int availableThreads, out int m);
|
||||
Logger.WriteDebug($"There are {workerThreads - availableThreads} active threading tasks");
|
||||
#endif
|
||||
try
|
||||
{
|
||||
await Task.Delay(ConfigHandler.Configuration().RConPollRate, token);
|
||||
}
|
||||
// if a cancellation is received, we want to return immediately
|
||||
catch { break; }
|
||||
}
|
||||
}
|
||||
|
||||
public async Task Init()
|
||||
{
|
||||
Running = true;
|
||||
ExternalIPAddress = await Utilities.GetExternalIP();
|
||||
|
||||
#region PLUGINS
|
||||
SharedLibraryCore.Plugins.PluginImporter.Load(this);
|
||||
|
||||
foreach (var Plugin in SharedLibraryCore.Plugins.PluginImporter.ActivePlugins)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Plugin.OnLoadAsync(this);
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.WriteError($"{Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_PLUGIN"]} {Plugin.Name}");
|
||||
Logger.WriteDebug(ex.GetExceptionInfo());
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region CONFIG
|
||||
var config = ConfigHandler.Configuration();
|
||||
|
||||
// copy over default config if it doesn't exist
|
||||
if (config == null)
|
||||
{
|
||||
var defaultConfig = new BaseConfigurationHandler<DefaultConfiguration>("DefaultSettings").Configuration();
|
||||
ConfigHandler.Set((ApplicationConfiguration)new ApplicationConfiguration().Generate());
|
||||
var newConfig = ConfigHandler.Configuration();
|
||||
|
||||
newConfig.AutoMessages = defaultConfig.AutoMessages;
|
||||
newConfig.GlobalRules = defaultConfig.GlobalRules;
|
||||
newConfig.Maps = defaultConfig.Maps;
|
||||
newConfig.DisallowedClientNames = defaultConfig.DisallowedClientNames;
|
||||
newConfig.QuickMessages = defaultConfig.QuickMessages;
|
||||
|
||||
if (newConfig.Servers == null)
|
||||
{
|
||||
ConfigHandler.Set(newConfig);
|
||||
newConfig.Servers = new List<ServerConfiguration>();
|
||||
|
||||
do
|
||||
{
|
||||
var serverConfig = new ServerConfiguration();
|
||||
foreach (var parser in AdditionalRConParsers)
|
||||
{
|
||||
serverConfig.AddRConParser(parser);
|
||||
}
|
||||
|
||||
foreach (var parser in AdditionalEventParsers)
|
||||
{
|
||||
serverConfig.AddEventParser(parser);
|
||||
}
|
||||
|
||||
newConfig.Servers.Add((ServerConfiguration)serverConfig.Generate());
|
||||
} while (Utilities.PromptBool(Utilities.CurrentLocalization.LocalizationIndex["SETUP_SERVER_SAVE"]));
|
||||
|
||||
config = newConfig;
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
if (string.IsNullOrEmpty(config.Id))
|
||||
{
|
||||
config.Id = Guid.NewGuid().ToString();
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(config.WebfrontBindUrl))
|
||||
{
|
||||
config.WebfrontBindUrl = "http://0.0.0.0:1624";
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
|
||||
foreach (var serverConfig in config.Servers)
|
||||
{
|
||||
Migration.ConfigurationMigration.ModifyLogPath020919(serverConfig);
|
||||
|
||||
if (serverConfig.RConParserVersion == null || serverConfig.EventParserVersion == null)
|
||||
{
|
||||
foreach (var parser in AdditionalRConParsers)
|
||||
{
|
||||
serverConfig.AddRConParser(parser);
|
||||
}
|
||||
|
||||
foreach (var parser in AdditionalEventParsers)
|
||||
{
|
||||
serverConfig.AddEventParser(parser);
|
||||
}
|
||||
|
||||
serverConfig.ModifyParsers();
|
||||
}
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
}
|
||||
|
||||
if (config.Servers.Count == 0)
|
||||
{
|
||||
throw new ServerException("A server configuration in IW4MAdminSettings.json is invalid");
|
||||
}
|
||||
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Utilities.EncodingType = Encoding.GetEncoding(!string.IsNullOrEmpty(config.CustomParserEncoding) ? config.CustomParserEncoding : "windows-1252");
|
||||
|
||||
#endregion
|
||||
|
||||
#region DATABASE
|
||||
using (var db = new DatabaseContext(GetApplicationSettings().Configuration()?.ConnectionString,
|
||||
GetApplicationSettings().Configuration()?.DatabaseProvider))
|
||||
{
|
||||
await new ContextSeed(db).Seed();
|
||||
}
|
||||
|
||||
PrivilegedClients = (await ClientSvc.GetPrivilegedClients()).ToDictionary(_client => _client.ClientId);
|
||||
#endregion
|
||||
|
||||
#region COMMANDS
|
||||
if (ClientSvc.GetOwners().Result.Count == 0)
|
||||
{
|
||||
Commands.Add(new COwner());
|
||||
}
|
||||
|
||||
Commands.Add(new CQuit());
|
||||
Commands.Add(new CKick());
|
||||
Commands.Add(new CSay());
|
||||
Commands.Add(new CTempBan());
|
||||
Commands.Add(new CBan());
|
||||
Commands.Add(new CWhoAmI());
|
||||
Commands.Add(new CList());
|
||||
Commands.Add(new CHelp());
|
||||
Commands.Add(new CFastRestart());
|
||||
Commands.Add(new CMapRotate());
|
||||
Commands.Add(new CSetLevel());
|
||||
Commands.Add(new CUsage());
|
||||
Commands.Add(new CUptime());
|
||||
Commands.Add(new CWarn());
|
||||
Commands.Add(new CWarnClear());
|
||||
Commands.Add(new CUnban());
|
||||
Commands.Add(new CListAdmins());
|
||||
Commands.Add(new CLoadMap());
|
||||
Commands.Add(new CFindPlayer());
|
||||
Commands.Add(new CListRules());
|
||||
Commands.Add(new CPrivateMessage());
|
||||
Commands.Add(new CFlag());
|
||||
Commands.Add(new CUnflag());
|
||||
Commands.Add(new CReport());
|
||||
Commands.Add(new CListReports());
|
||||
Commands.Add(new CListBanInfo());
|
||||
Commands.Add(new CListAlias());
|
||||
Commands.Add(new CExecuteRCON());
|
||||
Commands.Add(new CPlugins());
|
||||
Commands.Add(new CIP());
|
||||
Commands.Add(new CMask());
|
||||
Commands.Add(new CPruneAdmins());
|
||||
Commands.Add(new CKillServer());
|
||||
Commands.Add(new CSetPassword());
|
||||
Commands.Add(new CPing());
|
||||
Commands.Add(new CSetGravatar());
|
||||
Commands.Add(new CNextMap());
|
||||
Commands.Add(new RequestTokenCommand());
|
||||
|
||||
foreach (Command C in SharedLibraryCore.Plugins.PluginImporter.ActiveCommands)
|
||||
{
|
||||
Commands.Add(C);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region META
|
||||
async Task<List<ProfileMeta>> getProfileMeta(int clientId, int offset, int count, DateTime? startAt)
|
||||
{
|
||||
var metaList = new List<ProfileMeta>();
|
||||
|
||||
// we don't want to return anything because it means we're trying to retrieve paged meta data
|
||||
if (count > 1)
|
||||
{
|
||||
return metaList;
|
||||
}
|
||||
|
||||
var lastMapMeta = await _metaService.GetPersistentMeta("LastMapPlayed", new EFClient() { ClientId = clientId });
|
||||
|
||||
if (lastMapMeta != null)
|
||||
{
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Id = lastMapMeta.MetaId,
|
||||
Key = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_LAST_MAP"],
|
||||
Value = lastMapMeta.Value,
|
||||
Show = true,
|
||||
Type = ProfileMeta.MetaType.Information,
|
||||
});
|
||||
}
|
||||
|
||||
var lastServerMeta = await _metaService.GetPersistentMeta("LastServerPlayed", new EFClient() { ClientId = clientId });
|
||||
|
||||
if (lastServerMeta != null)
|
||||
{
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Id = lastServerMeta.MetaId,
|
||||
Key = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_LAST_SERVER"],
|
||||
Value = lastServerMeta.Value,
|
||||
Show = true,
|
||||
Type = ProfileMeta.MetaType.Information
|
||||
});
|
||||
}
|
||||
|
||||
var client = await GetClientService().Get(clientId);
|
||||
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Id = client.ClientId,
|
||||
Key = $"{Utilities.CurrentLocalization.LocalizationIndex["GLOBAL_TIME_HOURS"]} {Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_PLAYER"]}",
|
||||
Value = Math.Round(client.TotalConnectionTime / 3600.0, 1).ToString("#,##0", new System.Globalization.CultureInfo(Utilities.CurrentLocalization.LocalizationName)),
|
||||
Show = true,
|
||||
Column = 1,
|
||||
Order = 0,
|
||||
Type = ProfileMeta.MetaType.Information
|
||||
});
|
||||
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Id = client.ClientId,
|
||||
Key = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_FSEEN"],
|
||||
Value = Utilities.GetTimePassed(client.FirstConnection, false),
|
||||
Show = true,
|
||||
Column = 1,
|
||||
Order = 1,
|
||||
Type = ProfileMeta.MetaType.Information
|
||||
});
|
||||
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Id = client.ClientId,
|
||||
Key = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_PROFILE_LSEEN"],
|
||||
Value = Utilities.GetTimePassed(client.LastConnection, false),
|
||||
Show = true,
|
||||
Column = 1,
|
||||
Order = 2,
|
||||
Type = ProfileMeta.MetaType.Information
|
||||
});
|
||||
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Id = client.ClientId,
|
||||
Key = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_CONNECTIONS"],
|
||||
Value = client.Connections.ToString("#,##0", new System.Globalization.CultureInfo(Utilities.CurrentLocalization.LocalizationName)),
|
||||
Show = true,
|
||||
Column = 1,
|
||||
Order = 3,
|
||||
Type = ProfileMeta.MetaType.Information
|
||||
});
|
||||
|
||||
metaList.Add(new ProfileMeta()
|
||||
{
|
||||
Key = Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_MASKED"],
|
||||
Value = client.Masked ? Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_TRUE"] : Utilities.CurrentLocalization.LocalizationIndex["WEBFRONT_CLIENT_META_FALSE"],
|
||||
Sensitive = true,
|
||||
Column = 1,
|
||||
Order = 4,
|
||||
Type = ProfileMeta.MetaType.Information
|
||||
});
|
||||
|
||||
return metaList;
|
||||
}
|
||||
|
||||
async Task<List<ProfileMeta>> getPenaltyMeta(int clientId, int offset, int count, DateTime? startAt)
|
||||
{
|
||||
if (count <= 1)
|
||||
{
|
||||
return new List<ProfileMeta>();
|
||||
}
|
||||
|
||||
var penalties = await GetPenaltyService().GetClientPenaltyForMetaAsync(clientId, count, offset, startAt);
|
||||
|
||||
return penalties.Select(_penalty => new ProfileMeta()
|
||||
{
|
||||
Id = _penalty.Id,
|
||||
Type = _penalty.PunisherId == clientId ? ProfileMeta.MetaType.Penalized : ProfileMeta.MetaType.ReceivedPenalty,
|
||||
Value = _penalty,
|
||||
When = _penalty.TimePunished,
|
||||
Sensitive = _penalty.Sensitive
|
||||
})
|
||||
.ToList();
|
||||
}
|
||||
|
||||
MetaService.AddRuntimeMeta(getProfileMeta);
|
||||
MetaService.AddRuntimeMeta(getPenaltyMeta);
|
||||
#endregion
|
||||
|
||||
#region INIT
|
||||
int failedServers = 0;
|
||||
int successServers = 0;
|
||||
Exception lastException = null;
|
||||
|
||||
async Task Init(ServerConfiguration Conf)
|
||||
{
|
||||
// setup the event handler after the class is initialized
|
||||
|
||||
Handler = new GameEventHandler(this);
|
||||
|
||||
try
|
||||
{
|
||||
var ServerInstance = new IW4MServer(this, Conf);
|
||||
await ServerInstance.Initialize();
|
||||
|
||||
lock (_servers)
|
||||
{
|
||||
_servers.Add(ServerInstance);
|
||||
}
|
||||
|
||||
Logger.WriteVerbose(Utilities.CurrentLocalization.LocalizationIndex["MANAGER_MONITORING_TEXT"].FormatExt(ServerInstance.Hostname));
|
||||
// add the start event for this server
|
||||
|
||||
var e = new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Start,
|
||||
Data = $"{ServerInstance.GameName} started",
|
||||
Owner = ServerInstance
|
||||
};
|
||||
|
||||
Handler.AddEvent(e);
|
||||
successServers++;
|
||||
}
|
||||
|
||||
catch (ServerException e)
|
||||
{
|
||||
Logger.WriteError(Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_UNFIXABLE"].FormatExt($"[{Conf.IPAddress}:{Conf.Port}]"));
|
||||
|
||||
if (e.GetType() == typeof(DvarException))
|
||||
{
|
||||
Logger.WriteDebug($"{Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_DVAR"].FormatExt((e as DvarException).Data["dvar_name"])} ({Utilities.CurrentLocalization.LocalizationIndex["SERVER_ERROR_DVAR_HELP"]})");
|
||||
}
|
||||
|
||||
else if (e.GetType() == typeof(NetworkException))
|
||||
{
|
||||
Logger.WriteDebug(e.Message);
|
||||
}
|
||||
|
||||
failedServers++;
|
||||
lastException = e;
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(config.Servers.Select(c => Init(c)).ToArray());
|
||||
|
||||
if (successServers - failedServers <= 0)
|
||||
{
|
||||
if (!Utilities.PromptBool(Utilities.CurrentLocalization.LocalizationIndex["MANAGER_START_WITH_ERRORS"]))
|
||||
{
|
||||
throw lastException;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
private async Task SendHeartbeat(object state)
|
||||
{
|
||||
var heartbeatState = (HeartbeatState)state;
|
||||
|
||||
while (Running)
|
||||
{
|
||||
if (!heartbeatState.Connected)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Heartbeat.Send(this, true);
|
||||
heartbeatState.Connected = true;
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
heartbeatState.Connected = false;
|
||||
Logger.WriteWarning($"Could not connect to heartbeat server - {e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
await Heartbeat.Send(this);
|
||||
}
|
||||
|
||||
catch (System.Net.Http.HttpRequestException e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
}
|
||||
|
||||
catch (AggregateException e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
var exceptions = e.InnerExceptions.Where(ex => ex.GetType() == typeof(RestEase.ApiException));
|
||||
|
||||
foreach (var ex in exceptions)
|
||||
{
|
||||
if (((RestEase.ApiException)ex).StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
heartbeatState.Connected = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
catch (RestEase.ApiException e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
if (e.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
heartbeatState.Connected = false;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(30000, heartbeatState.Token);
|
||||
}
|
||||
catch { break; }
|
||||
}
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
var tokenSource = new CancellationTokenSource();
|
||||
// this needs to be run seperately from the main thread
|
||||
_ = Task.Run(() => SendHeartbeat(new HeartbeatState() { Token = tokenSource.Token }));
|
||||
_ = Task.Run(() => UpdateServerStates(tokenSource.Token));
|
||||
|
||||
while (Running)
|
||||
{
|
||||
OnQuit.Wait();
|
||||
tokenSource.Cancel();
|
||||
OnQuit.Reset();
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
Running = false;
|
||||
OnQuit.Set();
|
||||
}
|
||||
|
||||
public ILogger GetLogger(long serverId)
|
||||
{
|
||||
if (Loggers.ContainsKey(serverId))
|
||||
{
|
||||
return Loggers[serverId];
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
Logger newLogger;
|
||||
|
||||
if (serverId == 0)
|
||||
{
|
||||
newLogger = new Logger("IW4MAdmin-Manager");
|
||||
}
|
||||
else
|
||||
{
|
||||
newLogger = new Logger($"IW4MAdmin-Server-{serverId}");
|
||||
}
|
||||
|
||||
Loggers.Add(serverId, newLogger);
|
||||
return newLogger;
|
||||
}
|
||||
}
|
||||
|
||||
public IList<MessageToken> GetMessageTokens()
|
||||
{
|
||||
return MessageTokens;
|
||||
}
|
||||
|
||||
public IList<EFClient> GetActiveClients()
|
||||
{
|
||||
return _servers.SelectMany(s => s.Clients).Where(p => p != null).ToList();
|
||||
}
|
||||
|
||||
public ClientService GetClientService()
|
||||
{
|
||||
return ClientSvc;
|
||||
}
|
||||
|
||||
public AliasService GetAliasService()
|
||||
{
|
||||
return AliasSvc;
|
||||
}
|
||||
|
||||
public PenaltyService GetPenaltyService()
|
||||
{
|
||||
return PenaltySvc;
|
||||
}
|
||||
|
||||
public IConfigurationHandler<ApplicationConfiguration> GetApplicationSettings()
|
||||
{
|
||||
return ConfigHandler;
|
||||
}
|
||||
|
||||
public IDictionary<int, EFClient> GetPrivilegedClients()
|
||||
{
|
||||
return PrivilegedClients;
|
||||
}
|
||||
|
||||
public bool ShutdownRequested()
|
||||
{
|
||||
return !Running;
|
||||
}
|
||||
|
||||
public IEventHandler GetEventHandler()
|
||||
{
|
||||
return Handler;
|
||||
}
|
||||
|
||||
public void SetHasEvent()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
public IList<Assembly> GetPluginAssemblies()
|
||||
{
|
||||
return SharedLibraryCore.Plugins.PluginImporter.PluginAssemblies.Union(SharedLibraryCore.Plugins.PluginImporter.Assemblies).ToList();
|
||||
}
|
||||
|
||||
public IPageList GetPageList()
|
||||
{
|
||||
return PageList;
|
||||
}
|
||||
|
||||
public IRConParser GenerateDynamicRConParser()
|
||||
{
|
||||
return new DynamicRConParser();
|
||||
}
|
||||
|
||||
public IEventParser GenerateDynamicEventParser()
|
||||
{
|
||||
return new DynamicEventParser();
|
||||
}
|
||||
}
|
||||
}
|
@ -2,6 +2,9 @@ set SolutionDir=%1
|
||||
set ProjectDir=%2
|
||||
set TargetDir=%3
|
||||
set OutDir=%4
|
||||
set Version=%5
|
||||
|
||||
echo %Version% > "%SolutionDir%DEPLOY\version.txt"
|
||||
|
||||
echo Copying dependency configs
|
||||
copy "%SolutionDir%WebfrontCore\%OutDir%*.deps.json" "%TargetDir%"
|
||||
@ -15,4 +18,17 @@ if not exist "%TargetDir%Plugins" (
|
||||
xcopy /y "%SolutionDir%Build\Plugins" "%TargetDir%Plugins\"
|
||||
|
||||
echo Copying plugins for publish
|
||||
xcopy /Y "%SolutionDir%BUILD\Plugins" "%SolutionDir%Publish\Windows\Plugins\"
|
||||
del %SolutionDir%BUILD\Plugins\Tests.dll
|
||||
xcopy /Y "%SolutionDir%BUILD\Plugins" "%SolutionDir%Publish\Windows\Plugins\"
|
||||
xcopy /Y "%SolutionDir%BUILD\Plugins" "%SolutionDir%Publish\WindowsPrerelease\Plugins\"
|
||||
|
||||
echo Copying script plugins for publish
|
||||
xcopy /Y "%SolutionDir%Plugins\ScriptPlugins" "%SolutionDir%Publish\Windows\Plugins\"
|
||||
xcopy /Y "%SolutionDir%Plugins\ScriptPlugins" "%SolutionDir%Publish\WindowsPrerelease\Plugins\"
|
||||
|
||||
echo Copying GSC files for publish
|
||||
xcopy /Y "%SolutionDir%_customcallbacks.gsc" "%SolutionDir%Publish\Windows\userraw\scripts\"
|
||||
xcopy /Y "%SolutionDir%_customcallbacks.gsc" "%SolutionDir%Publish\WindowsPrerelease\userraw\scripts\"
|
||||
|
||||
xcopy /Y "%SolutionDir%_commands.gsc" "%SolutionDir%Publish\Windows\userraw\scripts\"
|
||||
xcopy /Y "%SolutionDir%_commands.gsc" "%SolutionDir%Publish\WindowsPrerelease\userraw\scripts\"
|
@ -1,8 +1,12 @@
|
||||
set SolutionDir=%1
|
||||
set ProjectDir=%2
|
||||
set TargetDir=%3
|
||||
set CurrentConfiguration=%4
|
||||
SET COPYCMD=/Y
|
||||
|
||||
echo Deleting extra language files
|
||||
|
||||
if exist "%SolutionDir%Publish\Windows\en-US\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\en-US'
|
||||
if exist "%SolutionDir%Publish\Windows\de\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\de'
|
||||
if exist "%SolutionDir%Publish\Windows\es\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\es'
|
||||
if exist "%SolutionDir%Publish\Windows\fr\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\fr'
|
||||
@ -13,6 +17,17 @@ if exist "%SolutionDir%Publish\Windows\ru\" powershell Remove-Item -Force -Recur
|
||||
if exist "%SolutionDir%Publish\Windows\zh-Hans\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\zh-Hans'
|
||||
if exist "%SolutionDir%Publish\Windows\zh-Hant\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\zh-Hant'
|
||||
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\en-US\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\en-US'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\de\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\de'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\es\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\es'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\fr\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\fr'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\it\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\it'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\ja\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\ja'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\ko\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\ko'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\ru\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\ru'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\zh-Hans\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\zh-Hans'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\zh-Hant\" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\zh-Hant'
|
||||
|
||||
echo Deleting extra runtime files
|
||||
if exist "%SolutionDir%Publish\Windows\runtimes\linux-arm" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\runtimes\linux-arm'
|
||||
if exist "%SolutionDir%Publish\Windows\runtimes\linux-arm64" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\runtimes\linux-arm64'
|
||||
@ -24,6 +39,77 @@ if exist "%SolutionDir%Publish\Windows\runtimes\osx-x64" powershell Remove-Item
|
||||
if exist "%SolutionDir%Publish\Windows\runtimes\win-arm" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\runtimes\win-arm'
|
||||
if exist "%SolutionDir%Publish\Windows\runtimes\win-arm64" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\Windows\runtimes\win-arm64'
|
||||
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\linux-arm" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\linux-arm'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\linux-arm64" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\linux-arm64'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\linux-armel" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\linux-armel'
|
||||
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\osx" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\osx'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\osx-x64" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\osx-x64'
|
||||
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\win-arm" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\win-arm'
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\runtimes\win-arm64" powershell Remove-Item -Force -Recurse '%SolutionDir%Publish\WindowsPrerelease\runtimes\win-arm64'
|
||||
|
||||
echo Deleting misc files
|
||||
if exist "%SolutionDir%Publish\Windows\web.config" del "%SolutionDir%Publish\Windows\web.config"
|
||||
del "%SolutionDir%Publish\Windows\*pdb"
|
||||
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\web.config" del "%SolutionDir%Publish\WindowsPrerelease\web.config"
|
||||
del "%SolutionDir%Publish\WindowsPrerelease\*pdb"
|
||||
|
||||
echo setting up library folders
|
||||
|
||||
if "%CurrentConfiguration%" == "Prerelease" (
|
||||
echo PR-Config
|
||||
if not exist "%SolutionDir%Publish\WindowsPrerelease\Configuration" md "%SolutionDir%Publish\WindowsPrerelease\Configuration"
|
||||
move "%SolutionDir%Publish\WindowsPrerelease\DefaultSettings.json" "%SolutionDir%Publish\WindowsPrerelease\Configuration\"
|
||||
)
|
||||
|
||||
if "%CurrentConfiguration%" == "Release" (
|
||||
echo R-Config
|
||||
if not exist "%SolutionDir%Publish\Windows\Configuration" md "%SolutionDir%Publish\Windows\Configuration"
|
||||
if exist "%SolutionDir%Publish\Windows\DefaultSettings.json" move "%SolutionDir%Publish\Windows\DefaultSettings.json" "%SolutionDir%Publish\Windows\Configuration\DefaultSettings.json"
|
||||
)
|
||||
|
||||
if "%CurrentConfiguration%" == "Prerelease" (
|
||||
echo PR-LIB
|
||||
if not exist "%SolutionDir%Publish\WindowsPrerelease\Lib\" md "%SolutionDir%Publish\WindowsPrerelease\Lib\"
|
||||
move "%SolutionDir%Publish\WindowsPrerelease\*.dll" "%SolutionDir%Publish\WindowsPrerelease\Lib\"
|
||||
move "%SolutionDir%Publish\WindowsPrerelease\*.json" "%SolutionDir%Publish\WindowsPrerelease\Lib\"
|
||||
)
|
||||
|
||||
if "%CurrentConfiguration%" == "Release" (
|
||||
echo R-LIB
|
||||
if not exist "%SolutionDir%Publish\Windows\Lib\" md "%SolutionDir%Publish\Windows\Lib\"
|
||||
move "%SolutionDir%Publish\Windows\*.dll" "%SolutionDir%Publish\Windows\Lib\"
|
||||
move "%SolutionDir%Publish\Windows\*.json" "%SolutionDir%Publish\Windows\Lib\"
|
||||
)
|
||||
|
||||
if "%CurrentConfiguration%" == "Prerelease" (
|
||||
echo PR-RT
|
||||
move "%SolutionDir%Publish\WindowsPrerelease\runtimes" "%SolutionDir%Publish\WindowsPrerelease\Lib\runtimes"
|
||||
if exist "%SolutionDir%Publish\WindowsPrerelease\refs" move "%SolutionDir%Publish\WindowsPrerelease\refs" "%SolutionDir%Publish\WindowsPrerelease\Lib\refs"
|
||||
)
|
||||
|
||||
|
||||
if "%CurrentConfiguration%" == "Release" (
|
||||
echo R-RT
|
||||
move "%SolutionDir%Publish\Windows\runtimes" "%SolutionDir%Publish\Windows\Lib\runtimes"
|
||||
if exist "%SolutionDir%Publish\Windows\refs" move "%SolutionDir%Publish\Windows\refs" "%SolutionDir%Publish\Windows\Lib\refs"
|
||||
)
|
||||
|
||||
if "%CurrentConfiguration%" == "Prerelease" (
|
||||
echo PR-LOC
|
||||
if not exist "%SolutionDir%Publish\WindowsPrerelease\Localization" md "%SolutionDir%Publish\WindowsPrerelease\Localization"
|
||||
)
|
||||
|
||||
if "%CurrentConfiguration%" == "Release" (
|
||||
echo R-LOC
|
||||
if not exist "%SolutionDir%Publish\Windows\Localization" md "%SolutionDir%Publish\Windows\Localization"
|
||||
)
|
||||
|
||||
echo making start scripts
|
||||
@(echo @echo off && echo @title IW4MAdmin && echo dotnet Lib\IW4MAdmin.dll && echo pause) > "%SolutionDir%Publish\WindowsPrerelease\StartIW4MAdmin.cmd"
|
||||
@(echo @echo off && echo @title IW4MAdmin && echo dotnet Lib\IW4MAdmin.dll && echo pause) > "%SolutionDir%Publish\Windows\StartIW4MAdmin.cmd"
|
||||
|
||||
@(echo #!/bin/bash && echo dotnet Lib/IW4MAdmin.dll) > "%SolutionDir%Publish\WindowsPrerelease\StartIW4MAdmin.sh"
|
||||
@(echo #!/bin/bash && echo dotnet Lib/IW4MAdmin.dll) > "%SolutionDir%Publish\Windows\StartIW4MAdmin.sh"
|
||||
|
@ -1,62 +0,0 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
class ConfigurationGenerator
|
||||
{
|
||||
public static List<ServerConfiguration> GenerateServerConfig(List<ServerConfiguration> configList)
|
||||
{
|
||||
|
||||
var loc = Utilities.CurrentLocalization.LocalizationSet;
|
||||
var newConfig = new ServerConfiguration();
|
||||
|
||||
while (string.IsNullOrEmpty(newConfig.IPAddress))
|
||||
{
|
||||
try
|
||||
{
|
||||
string input = Utilities.PromptString(loc["SETUP_SERVER_IP"]);
|
||||
IPAddress.Parse(input);
|
||||
newConfig.IPAddress = input;
|
||||
}
|
||||
|
||||
catch (Exception)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
while (newConfig.Port == 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
newConfig.Port = Int16.Parse(Utilities.PromptString(loc["SETUP_SERVER_PORT"]));
|
||||
}
|
||||
|
||||
catch (Exception)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
newConfig.Password = Utilities.PromptString(loc["SETUP_SERVER_RCON"]);
|
||||
newConfig.AutoMessages = new List<string>();
|
||||
newConfig.Rules = new List<string>();
|
||||
|
||||
newConfig.UseT6MParser = Utilities.PromptBool(loc["SETUP_SERVER_USET6M"]);
|
||||
|
||||
configList.Add(newConfig);
|
||||
|
||||
if (Utilities.PromptBool(loc["SETUP_SERVER_SAVE"]))
|
||||
GenerateServerConfig(configList);
|
||||
|
||||
return configList;
|
||||
}
|
||||
}
|
||||
}
|
@ -3,6 +3,7 @@
|
||||
"AutoMessages": [
|
||||
"This server uses ^5IW4M Admin v{{VERSION}} ^7get it at ^5raidmax.org/IW4MAdmin",
|
||||
"^5IW4M Admin ^7sees ^5YOU!",
|
||||
"{{TOPSTATS}}",
|
||||
"This server has seen a total of ^5{{TOTALPLAYERS}} ^7players!",
|
||||
"Cheaters are ^1unwelcome ^7 on this server",
|
||||
"Did you know 8/10 people agree with unverified statistics?"
|
||||
@ -15,7 +16,231 @@
|
||||
"Keep grenade launcher use to a minimum",
|
||||
"Balance teams at ALL times"
|
||||
],
|
||||
"DisallowedClientNames": ["Unknown Soldier", "VickNet", "UnknownSoldier", "CHEATER"],
|
||||
"QuickMessages": [
|
||||
{
|
||||
"Game": "IW4",
|
||||
"Messages": {
|
||||
"QUICKMESSAGE_AREA_SECURE": "Area secure!",
|
||||
"QUICKMESSAGE_ARE_YOU_CRAZY": "Are you crazy?",
|
||||
"QUICKMESSAGE_ATTACK_LEFT_FLANK": "Attack left flank!",
|
||||
"QUICKMESSAGE_ATTACK_RIGHT_FLANK": "Attack right flank!",
|
||||
"QUICKMESSAGE_COME_ON": "Come on.",
|
||||
"QUICKMESSAGE_ENEMIES_SPOTTED": "Multiple contacts!",
|
||||
"QUICKMESSAGE_ENEMY_DOWN": "Enemy down!",
|
||||
"QUICKMESSAGE_ENEMY_GRENADE": "Enemy grenade!",
|
||||
"QUICKMESSAGE_ENEMY_SPOTTED": "Contact!",
|
||||
"QUICKMESSAGE_FALL_BACK": "Fall back!",
|
||||
"QUICKMESSAGE_FOLLOW_ME": "On me!",
|
||||
"QUICKMESSAGE_GREAT_SHOT": "Nice shot!",
|
||||
"QUICKMESSAGE_GRENADE": "Grenade!",
|
||||
"QUICKMESSAGE_HOLD_THIS_POSITION": "Hold this position!",
|
||||
"QUICKMESSAGE_HOLD_YOUR_FIRE": "Hold your fire!",
|
||||
"QUICKMESSAGE_IM_IN_POSITION": "In position.",
|
||||
"QUICKMESSAGE_IM_ON_MY_WAY": "Moving.",
|
||||
"QUICKMESSAGE_MOVE_IN": "Move in!",
|
||||
"QUICKMESSAGE_NEED_REINFORCEMENTS": "Need reinforcements!",
|
||||
"QUICKMESSAGE_NO_SIR": "Negative.",
|
||||
"QUICKMESSAGE_ON_MY_WAY": "On my way.",
|
||||
"QUICKMESSAGE_REGROUP": "Regroup!",
|
||||
"QUICKMESSAGE_SNIPER": "Sniper!",
|
||||
"QUICKMESSAGE_SORRY": "Sorry.",
|
||||
"QUICKMESSAGE_SQUAD_ATTACK_LEFT_FLANK": "Squad, attack left flank!",
|
||||
"QUICKMESSAGE_SQUAD_ATTACK_RIGHT_FLANK": "Squad, attack right flank!",
|
||||
"QUICKMESSAGE_SQUAD_HOLD_THIS_POSITION": "Squad, hold this position!",
|
||||
"QUICKMESSAGE_SQUAD_REGROUP": "Squad, regroup!",
|
||||
"QUICKMESSAGE_SQUAD_STICK_TOGETHER": "Squad, stick together!",
|
||||
"QUICKMESSAGE_STICK_TOGETHER": "Stick together!",
|
||||
"QUICKMESSAGE_SUPPRESSING_FIRE": "Base of fire!",
|
||||
"QUICKMESSAGE_TOOK_LONG_ENOUGH": "Took long enough!",
|
||||
"QUICKMESSAGE_TOOK_YOU_LONG_ENOUGH": "Took you long enough!",
|
||||
"QUICKMESSAGE_WATCH_SIX": "Watch your six!",
|
||||
"QUICKMESSAGE_YES_SIR": "Roger.",
|
||||
"QUICKMESSAGE_YOURE_CRAZY": "You're crazy!",
|
||||
"QUICKMESSAGE_YOURE_NUTS": "You're nuts!",
|
||||
"QUICKMESSAGE_YOU_OUTTA_YOUR_MIND": "You outta your mind?"
|
||||
}
|
||||
}
|
||||
],
|
||||
"Maps": [
|
||||
{
|
||||
"Game": "IW3",
|
||||
"Maps": [
|
||||
{
|
||||
"Alias": "Ambush",
|
||||
"Name": "mp_convoy"
|
||||
},
|
||||
{
|
||||
"Alias": "Backlot",
|
||||
"Name": "mp_backlot"
|
||||
},
|
||||
{
|
||||
"Alias": "Bloc",
|
||||
"Name": "mp_bloc"
|
||||
},
|
||||
{
|
||||
"Alias": "Bog",
|
||||
"Name": "mp_bog"
|
||||
},
|
||||
{
|
||||
"Alias": "Countdown",
|
||||
"Name": "mp_countdown"
|
||||
},
|
||||
{
|
||||
"Alias": "Crash",
|
||||
"Name": "mp_crash"
|
||||
},
|
||||
{
|
||||
"Alias": "Crossfire",
|
||||
"Name": "mp_crossfire"
|
||||
},
|
||||
{
|
||||
"Alias": "District",
|
||||
"Name": "mp_citystreets"
|
||||
},
|
||||
{
|
||||
"Alias": "Downpour",
|
||||
"Name": "mp_farm"
|
||||
},
|
||||
{
|
||||
"Alias": "Overgrown",
|
||||
"Name": "mp_overgrown"
|
||||
},
|
||||
{
|
||||
"Alias": "Pipeline",
|
||||
"Name": "mp_pipeline"
|
||||
},
|
||||
{
|
||||
"Alias": "Shipment",
|
||||
"Name": "mp_shipment"
|
||||
},
|
||||
{
|
||||
"Alias": "Showdown",
|
||||
"Name": "mp_showdown"
|
||||
},
|
||||
{
|
||||
"Alias": "Strike",
|
||||
"Name": "mp_strike"
|
||||
},
|
||||
{
|
||||
"Alias": "Vacant",
|
||||
"Name": "mp_vacant"
|
||||
},
|
||||
{
|
||||
"Alias": "Wet Work",
|
||||
"Name": "mp_cargoship"
|
||||
},
|
||||
{
|
||||
"Alias": "Winter Crash",
|
||||
"Name": "mp_crash_snow"
|
||||
},
|
||||
{
|
||||
"Alias": "Broadcast",
|
||||
"Name": "mp_broadcast"
|
||||
},
|
||||
{
|
||||
"Alias": "Creek",
|
||||
"Name": "mp_creek"
|
||||
},
|
||||
{
|
||||
"Alias": "Chinatown",
|
||||
"Name": "mp_carentan"
|
||||
},
|
||||
{
|
||||
"Alias": "Killhouse",
|
||||
"Name": "mp_killhouse"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Game": "T4",
|
||||
"Maps": [
|
||||
{
|
||||
"Alias": "Airfield",
|
||||
"Name": "mp_airfield"
|
||||
},
|
||||
{
|
||||
"Alias": "Asylum",
|
||||
"Name": "mp_asylum"
|
||||
},
|
||||
{
|
||||
"Alias": "Castle",
|
||||
"Name": "mp_castle"
|
||||
},
|
||||
{
|
||||
"Alias": "Cliffside",
|
||||
"Name": "mp_shrine"
|
||||
},
|
||||
{
|
||||
"Alias": "Courtyard",
|
||||
"Name": "mp_courtyard"
|
||||
},
|
||||
{
|
||||
"Alias": "Dome",
|
||||
"Name": "mp_dome"
|
||||
},
|
||||
{
|
||||
"Alias": "Downfall",
|
||||
"Name": "mp_downfall"
|
||||
},
|
||||
{
|
||||
"Alias": "Hanger",
|
||||
"Name": "mp_hangar"
|
||||
},
|
||||
{
|
||||
"Alias": "Makin",
|
||||
"Name": "mp_makin"
|
||||
},
|
||||
{
|
||||
"Alias": "Outskirts",
|
||||
"Name": "mp_outskirts"
|
||||
},
|
||||
{
|
||||
"Alias": "Roundhouse",
|
||||
"Name": "mp_roundhouse"
|
||||
},
|
||||
{
|
||||
"Alias": "Upheaval",
|
||||
"Name": "mp_suburban"
|
||||
},
|
||||
{
|
||||
"Alias": "Knee Deep",
|
||||
"Name": "mp_kneedeep"
|
||||
},
|
||||
{
|
||||
"Alias": "Nightfire",
|
||||
"Name": "mp_nachtfeuer"
|
||||
},
|
||||
{
|
||||
"Alias": "Station",
|
||||
"Name": "mp_subway"
|
||||
},
|
||||
{
|
||||
"Alias": "Banzai",
|
||||
"Name": "mp_kwai"
|
||||
},
|
||||
{
|
||||
"Alias": "Corrosion",
|
||||
"Name": "mp_stalingrad"
|
||||
},
|
||||
{
|
||||
"Alias": "Sub Pens",
|
||||
"Name": "mp_docks"
|
||||
},
|
||||
{
|
||||
"Alias": "Battery",
|
||||
"Name": "mp_drum"
|
||||
},
|
||||
{
|
||||
"Alias": "Breach",
|
||||
"Name": "mp_bgate"
|
||||
},
|
||||
{
|
||||
"Alias": "Revolution",
|
||||
"Name": "mp_vodka"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Game": "IW4",
|
||||
"Maps": [
|
||||
@ -24,11 +249,6 @@
|
||||
"Name": "mp_rust"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Highrise",
|
||||
"Name": "mp_highrise"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Terminal",
|
||||
"Name": "mp_terminal"
|
||||
@ -39,16 +259,6 @@
|
||||
"Name": "mp_crash"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Skidrow",
|
||||
"Name": "mp_nightshift"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Quarry",
|
||||
"Name": "mp_quarry"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Afghan",
|
||||
"Name": "mp_afghan"
|
||||
@ -170,7 +380,7 @@
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "IW4 Credits",
|
||||
"Alias": "Test map",
|
||||
"Name": "iw4_credits"
|
||||
},
|
||||
|
||||
@ -189,6 +399,11 @@
|
||||
"Name": "mp_cargoship_sh"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Cargoship",
|
||||
"Name": "mp_cargoship"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Shipment",
|
||||
"Name": "mp_shipment"
|
||||
@ -215,28 +430,302 @@
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Favela - Tropical",
|
||||
"Alias": "Tropical Favela",
|
||||
"Name": "mp_fav_tropical"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Estate - Tropical",
|
||||
"Alias": "Tropical Estate",
|
||||
"Name": "mp_estate_tropical"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Crash - Tropical",
|
||||
"Alias": "Tropical Crash",
|
||||
"Name": "mp_crash_tropical"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Forgotten City",
|
||||
"Name": "mp_bloc_sh"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Crossfire",
|
||||
"Name": "mp_cross_fire"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Bloc",
|
||||
"Name": "mp_bloc"
|
||||
},
|
||||
|
||||
{
|
||||
"Alias": "Oilrig",
|
||||
"Name": "oilrig"
|
||||
},
|
||||
|
||||
{
|
||||
"Name": "Village",
|
||||
"Alias": "co_hunted"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Game": "T6M",
|
||||
"Game": "T5",
|
||||
"Maps": [
|
||||
{
|
||||
"Alias": "Array",
|
||||
"Name": "mp_array"
|
||||
},
|
||||
{
|
||||
"Alias": "Berlin Wall",
|
||||
"Name": "mp_berlinwall2"
|
||||
},
|
||||
{
|
||||
"Alias": "Convoy",
|
||||
"Name": "mp_gridlock"
|
||||
},
|
||||
{
|
||||
"Alias": "Cracked",
|
||||
"Name": "mp_cracked"
|
||||
},
|
||||
{
|
||||
"Alias": "Crisis",
|
||||
"Name": "mp_crisis"
|
||||
},
|
||||
{
|
||||
"Alias": "Discovery",
|
||||
"Name": "mp_discovery"
|
||||
},
|
||||
{
|
||||
"Alias": "Drive-In",
|
||||
"Name": "mp_drivein"
|
||||
},
|
||||
{
|
||||
"Alias": "Firing Range",
|
||||
"Name": "mp_firingrange"
|
||||
},
|
||||
{
|
||||
"Alias": "Grid",
|
||||
"Name": "mp_duga"
|
||||
},
|
||||
{
|
||||
"Alias": "Hangar 18",
|
||||
"Name": "mp_area51"
|
||||
},
|
||||
{
|
||||
"Alias": "Hanoi",
|
||||
"Name": "mp_hanoi"
|
||||
},
|
||||
{
|
||||
"Alias": "Hazard",
|
||||
"Name": "mp_golfcourse"
|
||||
},
|
||||
{
|
||||
"Alias": "Hotel",
|
||||
"Name": "mp_hotel"
|
||||
},
|
||||
{
|
||||
"Alias": "Jungle",
|
||||
"Name": "mp_havoc"
|
||||
},
|
||||
{
|
||||
"Alias": "Kowloon",
|
||||
"Name": "mp_kowloon"
|
||||
},
|
||||
{
|
||||
"Alias": "Launch",
|
||||
"Name": "mp_cosmodrome"
|
||||
},
|
||||
{
|
||||
"Alias": "Nuketown",
|
||||
"Name": "mp_nuked"
|
||||
},
|
||||
{
|
||||
"Alias": "Radiation",
|
||||
"Name": "mp_radiation"
|
||||
},
|
||||
{
|
||||
"Alias": "Silo",
|
||||
"Name": "mp_silo"
|
||||
},
|
||||
{
|
||||
"Alias": "Stadium",
|
||||
"Name": "mp_stadium"
|
||||
},
|
||||
{
|
||||
"Alias": "Stockpile",
|
||||
"Name": "mp_outskirts"
|
||||
},
|
||||
{
|
||||
"Alias": "Summit",
|
||||
"Name": "mp_mountain"
|
||||
},
|
||||
{
|
||||
"Alias": "Villa",
|
||||
"Name": "mp_villa"
|
||||
},
|
||||
{
|
||||
"Alias": "WMD",
|
||||
"Name": "mp_russianbase"
|
||||
},
|
||||
{
|
||||
"Alias": "Zoo",
|
||||
"Name": "mp_zoo"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Game": "IW5",
|
||||
"Maps": [
|
||||
{
|
||||
"Alias": "Seatown",
|
||||
"Name": "mp_seatown"
|
||||
},
|
||||
{
|
||||
"Alias": "Lockdown",
|
||||
"Name": "mp_alpha"
|
||||
},
|
||||
{
|
||||
"Alias": "Mission",
|
||||
"Name": "mp_bravo"
|
||||
},
|
||||
{
|
||||
"Alias": "Carbon",
|
||||
"Name": "mp_carbon"
|
||||
},
|
||||
{
|
||||
"Alias": "Dome",
|
||||
"Name": "mp_dome"
|
||||
},
|
||||
{
|
||||
"Alias": "Arkaden",
|
||||
"Name": "mp_plaza2"
|
||||
},
|
||||
{
|
||||
"Alias": "Downturn",
|
||||
"Name": "mp_exchange"
|
||||
},
|
||||
{
|
||||
"Alias": "Bootleg",
|
||||
"Name": "mp_bootleg"
|
||||
},
|
||||
{
|
||||
"Alias": "Hardhat",
|
||||
"Name": "mp_hardhat"
|
||||
},
|
||||
{
|
||||
"Alias": "Interchange",
|
||||
"Name": "mp_interchange"
|
||||
},
|
||||
{
|
||||
"Alias": "Fallen",
|
||||
"Name": "mp_lambeth"
|
||||
},
|
||||
{
|
||||
"Alias": "Outpost",
|
||||
"Name": "mp_radar"
|
||||
},
|
||||
{
|
||||
"Alias": "Bakaara",
|
||||
"Name": "mp_mogadishu"
|
||||
},
|
||||
{
|
||||
"Alias": "Resistance",
|
||||
"Name": "mp_paris"
|
||||
},
|
||||
{
|
||||
"Alias": "Underground",
|
||||
"Name": "mp_underground"
|
||||
},
|
||||
{
|
||||
"Alias": "Village",
|
||||
"Name": "mp_village"
|
||||
},
|
||||
{
|
||||
"Alias": "Aground",
|
||||
"Name": "mp_aground_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Boardwalk",
|
||||
"Name": "mp_boardwalk"
|
||||
},
|
||||
{
|
||||
"Alias": "U-turn",
|
||||
"Name": "mp_burn_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Foundation",
|
||||
"Name": "mp_cement"
|
||||
},
|
||||
{
|
||||
"Alias": "Erosion",
|
||||
"Name": "mp_courtyard_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Intersection",
|
||||
"Name": "mp_crosswalk_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Getaway",
|
||||
"Name": "mp_hillside_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Piazza",
|
||||
"Name": "mp_italy"
|
||||
},
|
||||
{
|
||||
"Alias": "Sanctuary",
|
||||
"Name": "mp_meteora"
|
||||
},
|
||||
{
|
||||
"Alias": "Gulch",
|
||||
"Name": "mp_moab"
|
||||
},
|
||||
{
|
||||
"Alias": "Black Box",
|
||||
"Name": "mp_morningwood"
|
||||
},
|
||||
{
|
||||
"Alias": "Parish",
|
||||
"Name": "mp_nola"
|
||||
},
|
||||
{
|
||||
"Alias": "Overwatch",
|
||||
"Name": "mp_overwatch"
|
||||
},
|
||||
{
|
||||
"Alias": "Liberation",
|
||||
"Name": "mp_park"
|
||||
},
|
||||
{
|
||||
"Alias": "Oasis",
|
||||
"Name": "mp_qadeem"
|
||||
},
|
||||
{
|
||||
"Alias": "Lookout",
|
||||
"Name": "mp_restrepo_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Off Shore",
|
||||
"Name": "mp_roughneck"
|
||||
},
|
||||
{
|
||||
"Alias": "Decommission",
|
||||
"Name": "mp_shipbreaker"
|
||||
},
|
||||
{
|
||||
"Alias": "Vortex",
|
||||
"Name": "mp_six_ss"
|
||||
},
|
||||
{
|
||||
"Alias": "Terminal",
|
||||
"Name": "mp_terminal_cls"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"Game": "T6",
|
||||
"Maps": [
|
||||
{
|
||||
"Alias": "Aftermath",
|
||||
|
328
Application/EventParsers/BaseEventParser.cs
Normal file
328
Application/EventParsers/BaseEventParser.cs
Normal file
@ -0,0 +1,328 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using static SharedLibraryCore.Server;
|
||||
|
||||
namespace IW4MAdmin.Application.EventParsers
|
||||
{
|
||||
class BaseEventParser : IEventParser
|
||||
{
|
||||
public BaseEventParser()
|
||||
{
|
||||
Configuration = new DynamicEventParserConfiguration()
|
||||
{
|
||||
GameDirectory = "main",
|
||||
};
|
||||
|
||||
Configuration.Say.Pattern = @"^(say|sayteam);(-?[A-Fa-f0-9_]{1,32});([0-9]+);(.+);(.*)$";
|
||||
Configuration.Say.AddMapping(ParserRegex.GroupType.EventType, 1);
|
||||
Configuration.Say.AddMapping(ParserRegex.GroupType.OriginNetworkId, 2);
|
||||
Configuration.Say.AddMapping(ParserRegex.GroupType.OriginClientNumber, 3);
|
||||
Configuration.Say.AddMapping(ParserRegex.GroupType.OriginName, 4);
|
||||
Configuration.Say.AddMapping(ParserRegex.GroupType.Message, 5);
|
||||
|
||||
Configuration.Quit.Pattern = @"^(Q);(-?[A-Fa-f0-9_]{1,32}|bot[0-9]+);([0-9]+);(.*)$";
|
||||
Configuration.Quit.AddMapping(ParserRegex.GroupType.EventType, 1);
|
||||
Configuration.Quit.AddMapping(ParserRegex.GroupType.OriginNetworkId, 2);
|
||||
Configuration.Quit.AddMapping(ParserRegex.GroupType.OriginClientNumber, 3);
|
||||
Configuration.Quit.AddMapping(ParserRegex.GroupType.OriginName, 4);
|
||||
|
||||
Configuration.Join.Pattern = @"^(J);(-?[A-Fa-f0-9_]{1,32}|bot[0-9]+);([0-9]+);(.*)$";
|
||||
Configuration.Join.AddMapping(ParserRegex.GroupType.EventType, 1);
|
||||
Configuration.Join.AddMapping(ParserRegex.GroupType.OriginNetworkId, 2);
|
||||
Configuration.Join.AddMapping(ParserRegex.GroupType.OriginClientNumber, 3);
|
||||
Configuration.Join.AddMapping(ParserRegex.GroupType.OriginName, 4);
|
||||
|
||||
Configuration.Damage.Pattern = @"^(D);(-?[A-Fa-f0-9_]{1,32}|bot[0-9]+);(-?[0-9]+);(axis|allies|world);(.{1,24});(-?[A-Fa-f0-9_]{1,32}|bot[0-9]+)?;-?([0-9]+);(axis|allies|world);(.{1,24})?;((?:[0-9]+|[a-z]+|_)+);([0-9]+);((?:[A-Z]|_)+);((?:[a-z]|_)+)$";
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.EventType, 1);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.TargetNetworkId, 2);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.TargetClientNumber, 3);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.TargetTeam, 4);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.TargetName, 5);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.OriginNetworkId, 6);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.OriginClientNumber, 7);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.OriginTeam, 8);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.OriginName, 9);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.Weapon, 10);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.Damage, 11);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.MeansOfDeath, 12);
|
||||
Configuration.Damage.AddMapping(ParserRegex.GroupType.HitLocation, 13);
|
||||
|
||||
Configuration.Kill.Pattern = @"^(K);(-?[A-Fa-f0-9_]{1,32}|bot[0-9]+);(-?[0-9]+);(axis|allies|world);(.{1,24});(-?[A-Fa-f0-9_]{1,32}|bot[0-9]+)?;-?([0-9]+);(axis|allies|world);(.{1,24})?;((?:[0-9]+|[a-z]+|_)+);([0-9]+);((?:[A-Z]|_)+);((?:[a-z]|_)+)$";
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.EventType, 1);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.TargetNetworkId, 2);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.TargetClientNumber, 3);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.TargetTeam, 4);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.TargetName, 5);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.OriginNetworkId, 6);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.OriginClientNumber, 7);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.OriginTeam, 8);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.OriginName, 9);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.Weapon, 10);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.Damage, 11);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.MeansOfDeath, 12);
|
||||
Configuration.Kill.AddMapping(ParserRegex.GroupType.HitLocation, 13);
|
||||
}
|
||||
|
||||
public IEventParserConfiguration Configuration { get; set; }
|
||||
|
||||
public string Version { get; set; } = "CoD";
|
||||
|
||||
public Game GameName { get; set; } = Game.COD;
|
||||
|
||||
public string URLProtocolFormat { get; set; } = "CoD://{{ip}}:{{port}}";
|
||||
|
||||
public virtual GameEvent GetEvent(Server server, string logLine)
|
||||
{
|
||||
logLine = Regex.Replace(logLine, @"([0-9]+:[0-9]+ |^[0-9]+ )", "").Trim();
|
||||
string[] lineSplit = logLine.Split(';');
|
||||
string eventType = lineSplit[0];
|
||||
|
||||
if (eventType == "JoinTeam")
|
||||
{
|
||||
var origin = server.GetClientsAsList()
|
||||
.FirstOrDefault(c => c.NetworkId == lineSplit[1].ConvertLong());
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.JoinTeam,
|
||||
Data = logLine,
|
||||
Origin = origin,
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType == "say" || eventType == "sayteam")
|
||||
{
|
||||
var matchResult = Regex.Match(logLine, Configuration.Say.Pattern);
|
||||
|
||||
if (matchResult.Success)
|
||||
{
|
||||
string message = matchResult
|
||||
.Groups[Configuration.Say.GroupMapping[ParserRegex.GroupType.Message]]
|
||||
.ToString()
|
||||
.Replace("\x15", "")
|
||||
.Trim();
|
||||
|
||||
var origin = server.GetClientsAsList()
|
||||
.First(c => c.NetworkId == matchResult.Groups[Configuration.Say.GroupMapping[ParserRegex.GroupType.OriginNetworkId]].ToString().ConvertLong());
|
||||
|
||||
if (message[0] == '!' || message[0] == '@')
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Command,
|
||||
Data = message,
|
||||
Origin = origin,
|
||||
Owner = server,
|
||||
Message = message
|
||||
};
|
||||
}
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Say,
|
||||
Data = message,
|
||||
Origin = origin,
|
||||
Owner = server,
|
||||
Message = message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (eventType == "K")
|
||||
{
|
||||
if (!server.CustomCallback)
|
||||
{
|
||||
var match = Regex.Match(logLine, Configuration.Kill.Pattern);
|
||||
|
||||
if (match.Success)
|
||||
{
|
||||
string originId = match.Groups[Configuration.Kill.GroupMapping[ParserRegex.GroupType.OriginNetworkId]].Value.ToString();
|
||||
string targetId = match.Groups[Configuration.Kill.GroupMapping[ParserRegex.GroupType.TargetNetworkId]].Value.ToString();
|
||||
|
||||
var origin = !string.IsNullOrEmpty(originId) ? server.GetClientsAsList()
|
||||
.First(c => c.NetworkId == originId.ConvertLong()) :
|
||||
Utilities.IW4MAdminClient(server);
|
||||
|
||||
var target = !string.IsNullOrEmpty(targetId) ? server.GetClientsAsList()
|
||||
.First(c => c.NetworkId == targetId.ConvertLong()) :
|
||||
Utilities.IW4MAdminClient(server);
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Kill,
|
||||
Data = logLine,
|
||||
Origin = origin,
|
||||
Target = target,
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (eventType == "ScriptKill")
|
||||
{
|
||||
long originId = lineSplit[1].ConvertLong();
|
||||
long targetId = lineSplit[2].ConvertLong();
|
||||
|
||||
var origin = originId == long.MinValue ? Utilities.IW4MAdminClient(server) :
|
||||
server.GetClientsAsList().First(c => c.NetworkId == originId);
|
||||
var target = targetId == long.MinValue ? Utilities.IW4MAdminClient(server) :
|
||||
server.GetClientsAsList().FirstOrDefault(c => c.NetworkId == targetId) ?? Utilities.IW4MAdminClient(server);
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.ScriptKill,
|
||||
Data = logLine,
|
||||
Origin = origin,
|
||||
Target = target,
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType == "ScriptDamage")
|
||||
{
|
||||
long originId = lineSplit[1].ConvertLong();
|
||||
long targetId = lineSplit[2].ConvertLong();
|
||||
|
||||
var origin = originId == long.MinValue ? Utilities.IW4MAdminClient(server) :
|
||||
server.GetClientsAsList().First(c => c.NetworkId == originId);
|
||||
var target = targetId == long.MinValue ? Utilities.IW4MAdminClient(server) :
|
||||
server.GetClientsAsList().FirstOrDefault(c => c.NetworkId == targetId) ?? Utilities.IW4MAdminClient(server);
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.ScriptDamage,
|
||||
Data = logLine,
|
||||
Origin = origin,
|
||||
Target = target,
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
// damage
|
||||
if (eventType == "D")
|
||||
{
|
||||
if (!server.CustomCallback)
|
||||
{
|
||||
var regexMatch = Regex.Match(logLine, Configuration.Damage.Pattern);
|
||||
|
||||
if (regexMatch.Success)
|
||||
{
|
||||
string originId = regexMatch.Groups[Configuration.Damage.GroupMapping[ParserRegex.GroupType.OriginNetworkId]].ToString();
|
||||
string targetId = regexMatch.Groups[Configuration.Damage.GroupMapping[ParserRegex.GroupType.TargetNetworkId]].ToString();
|
||||
|
||||
var origin = !string.IsNullOrEmpty(originId) ? server.GetClientsAsList()
|
||||
.First(c => c.NetworkId == originId.ConvertLong()) :
|
||||
Utilities.IW4MAdminClient(server);
|
||||
|
||||
var target = !string.IsNullOrEmpty(targetId) ? server.GetClientsAsList()
|
||||
.First(c => c.NetworkId == targetId.ConvertLong()) :
|
||||
Utilities.IW4MAdminClient(server);
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Damage,
|
||||
Data = logLine,
|
||||
Origin = origin,
|
||||
Target = target,
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// join
|
||||
if (eventType == "J")
|
||||
{
|
||||
var regexMatch = Regex.Match(logLine, Configuration.Join.Pattern);
|
||||
if (regexMatch.Success)
|
||||
{
|
||||
bool isBot = regexMatch.Groups[Configuration.Join.GroupMapping[ParserRegex.GroupType.OriginNetworkId]].ToString().Contains("bot");
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.PreConnect,
|
||||
Data = logLine,
|
||||
Owner = server,
|
||||
Origin = new EFClient()
|
||||
{
|
||||
CurrentAlias = new EFAlias()
|
||||
{
|
||||
Name = regexMatch.Groups[Configuration.Join.GroupMapping[ParserRegex.GroupType.OriginName]].ToString().StripColors(),
|
||||
},
|
||||
NetworkId = regexMatch.Groups[Configuration.Join.GroupMapping[ParserRegex.GroupType.OriginNetworkId]].ToString().ConvertLong(),
|
||||
ClientNumber = Convert.ToInt32(regexMatch.Groups[Configuration.Join.GroupMapping[ParserRegex.GroupType.OriginClientNumber]].ToString()),
|
||||
State = EFClient.ClientState.Connecting,
|
||||
CurrentServer = server,
|
||||
IsBot = isBot
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (eventType == "Q")
|
||||
{
|
||||
var regexMatch = Regex.Match(logLine, Configuration.Quit.Pattern);
|
||||
if (regexMatch.Success)
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.PreDisconnect,
|
||||
Data = logLine,
|
||||
Owner = server,
|
||||
Origin = new EFClient()
|
||||
{
|
||||
CurrentAlias = new EFAlias()
|
||||
{
|
||||
Name = regexMatch.Groups[Configuration.Quit.GroupMapping[ParserRegex.GroupType.OriginName]].ToString().StripColors()
|
||||
},
|
||||
NetworkId = regexMatch.Groups[Configuration.Quit.GroupMapping[ParserRegex.GroupType.OriginNetworkId]].ToString().ConvertLong(),
|
||||
ClientNumber = Convert.ToInt32(regexMatch.Groups[Configuration.Quit.GroupMapping[ParserRegex.GroupType.OriginClientNumber]].ToString()),
|
||||
State = EFClient.ClientState.Disconnecting
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (eventType.Contains("ExitLevel"))
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.MapEnd,
|
||||
Data = lineSplit[0],
|
||||
Origin = Utilities.IW4MAdminClient(server),
|
||||
Target = Utilities.IW4MAdminClient(server),
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (eventType.Contains("InitGame"))
|
||||
{
|
||||
string dump = eventType.Replace("InitGame: ", "");
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.MapChange,
|
||||
Data = lineSplit[0],
|
||||
Origin = Utilities.IW4MAdminClient(server),
|
||||
Target = Utilities.IW4MAdminClient(server),
|
||||
Owner = server,
|
||||
Extra = dump.DictionaryFromKeyValue()
|
||||
};
|
||||
}
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Unknown,
|
||||
Origin = Utilities.IW4MAdminClient(server),
|
||||
Target = Utilities.IW4MAdminClient(server),
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
15
Application/EventParsers/DynamicEventParser.cs
Normal file
15
Application/EventParsers/DynamicEventParser.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using static SharedLibraryCore.Server;
|
||||
|
||||
namespace IW4MAdmin.Application.EventParsers
|
||||
{
|
||||
/// <summary>
|
||||
/// empty generic implementation of the IEventParserConfiguration
|
||||
/// allows script plugins to generate dynamic event parsers
|
||||
/// </summary>
|
||||
sealed internal class DynamicEventParser : BaseEventParser
|
||||
{
|
||||
}
|
||||
}
|
19
Application/EventParsers/DynamicEventParserConfiguration.cs
Normal file
19
Application/EventParsers/DynamicEventParserConfiguration.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using SharedLibraryCore.Interfaces;
|
||||
|
||||
namespace IW4MAdmin.Application.EventParsers
|
||||
{
|
||||
/// <summary>
|
||||
/// generic implementation of the IEventParserConfiguration
|
||||
/// allows script plugins to generate dynamic configurations
|
||||
/// </summary>
|
||||
sealed internal class DynamicEventParserConfiguration : IEventParserConfiguration
|
||||
{
|
||||
public string GameDirectory { get; set; }
|
||||
public ParserRegex Say { get; set; } = new ParserRegex();
|
||||
public ParserRegex Join { get; set; } = new ParserRegex();
|
||||
public ParserRegex Quit { get; set; } = new ParserRegex();
|
||||
public ParserRegex Kill { get; set; } = new ParserRegex();
|
||||
public ParserRegex Damage { get; set; } = new ParserRegex();
|
||||
public ParserRegex Action { get; set; } = new ParserRegex();
|
||||
}
|
||||
}
|
@ -1,110 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
|
||||
namespace Application.EventParsers
|
||||
{
|
||||
class IW4EventParser : IEventParser
|
||||
{
|
||||
public GameEvent GetEvent(Server server, string logLine)
|
||||
{
|
||||
string[] lineSplit = logLine.Split(';');
|
||||
string cleanedEventLine = Regex.Replace(lineSplit[0], @"[0-9]+:[0-9]+\ ", "").Trim();
|
||||
|
||||
if (cleanedEventLine[0] == 'K')
|
||||
{
|
||||
if (!server.CustomCallback)
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Script,
|
||||
Data = logLine,
|
||||
Origin = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 6)),
|
||||
Target = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 2)),
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (cleanedEventLine == "say" || cleanedEventLine == "sayteam")
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Say,
|
||||
Data = lineSplit[4].Replace("\x15", ""),
|
||||
Origin = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 2)),
|
||||
Owner = server,
|
||||
Message = lineSplit[4].Replace("\x15", "")
|
||||
};
|
||||
}
|
||||
|
||||
if (cleanedEventLine.Contains("ScriptKill"))
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Script,
|
||||
Data = logLine,
|
||||
Origin = server.GetPlayersAsList().First(c => c.NetworkId == lineSplit[1].ConvertLong()),
|
||||
Target = server.GetPlayersAsList().First(c => c.NetworkId == lineSplit[2].ConvertLong()),
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (cleanedEventLine.Contains("ExitLevel"))
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.MapEnd,
|
||||
Data = lineSplit[0],
|
||||
Origin = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Target = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (cleanedEventLine.Contains("InitGame"))
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.MapChange,
|
||||
Data = lineSplit[0],
|
||||
Origin = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Target = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Unknown,
|
||||
Origin = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Target = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
// other parsers can derive from this parser so we make it virtual
|
||||
public virtual string GetGameDir() => "userraw";
|
||||
}
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace Application.EventParsers
|
||||
{
|
||||
class IW5EventParser : IW4EventParser
|
||||
{
|
||||
public override string GetGameDir() => "rzodemo";
|
||||
}
|
||||
}
|
@ -1,112 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
|
||||
namespace Application.EventParsers
|
||||
{
|
||||
class T6MEventParser : IEventParser
|
||||
{
|
||||
public GameEvent GetEvent(Server server, string logLine)
|
||||
{
|
||||
string cleanedLogLine = Regex.Replace(logLine, @"^ *[0-9]+:[0-9]+ *", "");
|
||||
string[] lineSplit = cleanedLogLine.Split(';');
|
||||
|
||||
if (lineSplit[0][0] == 'K')
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Script,
|
||||
Data = cleanedLogLine,
|
||||
Origin = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 6)),
|
||||
Target = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 2)),
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (lineSplit[0][0] == 'D')
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Damage,
|
||||
Data = cleanedLogLine,
|
||||
Origin = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 6)),
|
||||
Target = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 2)),
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
if (lineSplit[0] == "say" || lineSplit[0] == "sayteam")
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Say,
|
||||
Data = lineSplit[4],
|
||||
Origin = server.GetPlayersAsList().First(c => c.ClientNumber == Utilities.ClientIdFromString(lineSplit, 2)),
|
||||
Owner = server,
|
||||
Message = lineSplit[4]
|
||||
};
|
||||
}
|
||||
|
||||
if (lineSplit[0].Contains("ExitLevel"))
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.MapEnd,
|
||||
Data = lineSplit[0],
|
||||
Origin = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Target = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
/*if (lineSplit[0].Contains("ShutdownGame"))
|
||||
{
|
||||
|
||||
}*/
|
||||
|
||||
if (lineSplit[0].Contains("InitGame"))
|
||||
{
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.MapChange,
|
||||
Data = lineSplit[0],
|
||||
Origin = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Target = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
return new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Unknown,
|
||||
Origin = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Target = new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
},
|
||||
Owner = server
|
||||
};
|
||||
}
|
||||
|
||||
public string GetGameDir() => $"t6r{Path.DirectorySeparatorChar}data";
|
||||
}
|
||||
}
|
23
Application/GameEventHandler.cs
Normal file
23
Application/GameEventHandler.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Events;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
class GameEventHandler : IEventHandler
|
||||
{
|
||||
readonly IManager Manager;
|
||||
public GameEventHandler(IManager mgr)
|
||||
{
|
||||
Manager = mgr;
|
||||
}
|
||||
|
||||
public void AddEvent(GameEvent gameEvent)
|
||||
{
|
||||
((Manager as ApplicationManager).OnServerEvent)(this, new GameEventArgs(null, false, gameEvent));
|
||||
}
|
||||
}
|
||||
}
|
77
Application/IO/GameLogEventDetection.cs
Normal file
77
Application/IO/GameLogEventDetection.cs
Normal file
@ -0,0 +1,77 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Application.IO
|
||||
{
|
||||
class GameLogEventDetection
|
||||
{
|
||||
Server Server;
|
||||
long PreviousFileSize;
|
||||
IGameLogReader Reader;
|
||||
readonly string GameLogFile;
|
||||
|
||||
class EventState
|
||||
{
|
||||
public ILogger Log { get; set; }
|
||||
public string ServerId { get; set; }
|
||||
}
|
||||
|
||||
public GameLogEventDetection(Server server, string gameLogPath, Uri gameLogServerUri)
|
||||
{
|
||||
GameLogFile = gameLogPath;
|
||||
Reader = gameLogServerUri != null ? new GameLogReaderHttp(gameLogServerUri, gameLogPath, server.EventParser) : Reader = new GameLogReader(gameLogPath, server.EventParser);
|
||||
Server = server;
|
||||
}
|
||||
|
||||
public async Task PollForChanges()
|
||||
{
|
||||
while (!Server.Manager.ShutdownRequested())
|
||||
{
|
||||
if (Server.IsInitialized)
|
||||
{
|
||||
try
|
||||
{
|
||||
await UpdateLogEvents();
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
Server.Logger.WriteWarning($"Failed to update log event for {Server.EndPoint}");
|
||||
Server.Logger.WriteDebug($"Exception: {e.Message}");
|
||||
Server.Logger.WriteDebug($"StackTrace: {e.StackTrace}");
|
||||
}
|
||||
}
|
||||
Thread.Sleep(Reader.UpdateInterval);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task UpdateLogEvents()
|
||||
{
|
||||
long fileSize = Reader.Length;
|
||||
|
||||
if (PreviousFileSize == 0)
|
||||
PreviousFileSize = fileSize;
|
||||
|
||||
long fileDiff = fileSize - PreviousFileSize;
|
||||
|
||||
// this makes the http log get pulled
|
||||
if (fileDiff < 1 && fileSize != -1)
|
||||
return;
|
||||
|
||||
PreviousFileSize = fileSize;
|
||||
|
||||
var events = await Reader.ReadEventsFromLog(Server, fileDiff, 0);
|
||||
|
||||
foreach (var ev in events)
|
||||
{
|
||||
Server.Manager.GetEventHandler().AddEvent(ev);
|
||||
await ev.WaitAsync();
|
||||
}
|
||||
|
||||
PreviousFileSize = fileSize;
|
||||
}
|
||||
}
|
||||
}
|
70
Application/IO/GameLogReader.cs
Normal file
70
Application/IO/GameLogReader.cs
Normal file
@ -0,0 +1,70 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Application.IO
|
||||
{
|
||||
class GameLogReader : IGameLogReader
|
||||
{
|
||||
IEventParser Parser;
|
||||
readonly string LogFile;
|
||||
|
||||
public long Length => new FileInfo(LogFile).Length;
|
||||
|
||||
public int UpdateInterval => 300;
|
||||
|
||||
public GameLogReader(string logFile, IEventParser parser)
|
||||
{
|
||||
LogFile = logFile;
|
||||
Parser = parser;
|
||||
}
|
||||
|
||||
public async Task<ICollection<GameEvent>> ReadEventsFromLog(Server server, long fileSizeDiff, long startPosition)
|
||||
{
|
||||
// allocate the bytes for the new log lines
|
||||
List<string> logLines = new List<string>();
|
||||
|
||||
// open the file as a stream
|
||||
using (var rd = new StreamReader(new FileStream(LogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Utilities.EncodingType))
|
||||
{
|
||||
// todo: max async
|
||||
// take the old start position and go back the number of new characters
|
||||
rd.BaseStream.Seek(-fileSizeDiff, SeekOrigin.End);
|
||||
|
||||
string newLine;
|
||||
while (!string.IsNullOrEmpty(newLine = await rd.ReadLineAsync()))
|
||||
{
|
||||
logLines.Add(newLine);
|
||||
}
|
||||
}
|
||||
|
||||
List<GameEvent> events = new List<GameEvent>();
|
||||
|
||||
// parse each line
|
||||
foreach (string eventLine in logLines)
|
||||
{
|
||||
if (eventLine.Length > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
// todo: catch elsewhere
|
||||
events.Add(Parser.GetEvent(server, eventLine));
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
server.Logger.WriteWarning("Could not properly parse event line");
|
||||
server.Logger.WriteDebug(e.Message);
|
||||
server.Logger.WriteDebug(eventLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
}
|
74
Application/IO/GameLogReaderHttp.cs
Normal file
74
Application/IO/GameLogReaderHttp.cs
Normal file
@ -0,0 +1,74 @@
|
||||
using IW4MAdmin.Application.API.GameLogServer;
|
||||
using RestEase;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using static SharedLibraryCore.Utilities;
|
||||
|
||||
namespace IW4MAdmin.Application.IO
|
||||
{
|
||||
/// <summary>
|
||||
/// provides capibility of reading log files over HTTP
|
||||
/// </summary>
|
||||
class GameLogReaderHttp : IGameLogReader
|
||||
{
|
||||
readonly IEventParser Parser;
|
||||
readonly IGameLogServer Api;
|
||||
readonly string logPath;
|
||||
|
||||
public GameLogReaderHttp(Uri gameLogServerUri, string logPath, IEventParser parser)
|
||||
{
|
||||
this.logPath = logPath.ToBase64UrlSafeString(); ;
|
||||
Parser = parser;
|
||||
Api = RestClient.For<IGameLogServer>(gameLogServerUri);
|
||||
}
|
||||
|
||||
public long Length => -1;
|
||||
|
||||
public int UpdateInterval => 350;
|
||||
|
||||
public async Task<ICollection<GameEvent>> ReadEventsFromLog(Server server, long fileSizeDiff, long startPosition)
|
||||
{
|
||||
#if DEBUG == true
|
||||
server.Logger.WriteDebug($"Begin reading from http log");
|
||||
#endif
|
||||
var events = new List<GameEvent>();
|
||||
string b64Path = logPath;
|
||||
var response = await Api.Log(b64Path);
|
||||
|
||||
if (!response.Success)
|
||||
{
|
||||
server.Logger.WriteError($"Could not get log server info of {logPath}/{b64Path} ({server.LogPath})");
|
||||
return events;
|
||||
}
|
||||
|
||||
// parse each line
|
||||
foreach (string eventLine in response.Data.Split(Environment.NewLine))
|
||||
{
|
||||
if (eventLine.Length > 0)
|
||||
{
|
||||
try
|
||||
{
|
||||
var e = Parser.GetEvent(server, eventLine);
|
||||
#if DEBUG == true
|
||||
server.Logger.WriteDebug($"Parsed event with id {e.Id} from http");
|
||||
#endif
|
||||
events.Add(e);
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
server.Logger.WriteWarning("Could not properly parse event line");
|
||||
server.Logger.WriteDebug(e.Message);
|
||||
server.Logger.WriteDebug(eventLine);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
}
|
1068
Application/IW4MServer.cs
Normal file
1068
Application/IW4MServer.cs
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,33 +1,78 @@
|
||||
using SharedLibraryCore;
|
||||
using IW4MAdmin.Application.API.Master;
|
||||
using SharedLibraryCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Application.Localization
|
||||
{
|
||||
public class Configure
|
||||
{
|
||||
public static void Initialize()
|
||||
public static void Initialize(string customLocale = null)
|
||||
{
|
||||
string currentLocal = CultureInfo.CurrentCulture.Name;
|
||||
string localizationFile = $"Localization{Path.DirectorySeparatorChar}IW4MAdmin.{currentLocal}.json";
|
||||
string localizationContents;
|
||||
string currentLocale = string.IsNullOrEmpty(customLocale) ? CultureInfo.CurrentCulture.Name : customLocale;
|
||||
string[] localizationFiles = Directory.GetFiles(Path.Join(Utilities.OperatingDirectory, "Localization"), $"*.{currentLocale}.json");
|
||||
|
||||
if (File.Exists(localizationFile))
|
||||
if (!Program.ServerManager.GetApplicationSettings()?.Configuration()?.UseLocalTranslations ?? false)
|
||||
{
|
||||
localizationContents = File.ReadAllText(localizationFile);
|
||||
|
||||
try
|
||||
{
|
||||
var api = Endpoint.Get();
|
||||
var localization = api.GetLocalization(currentLocale).Result;
|
||||
Utilities.CurrentLocalization = localization;
|
||||
return;
|
||||
}
|
||||
|
||||
catch (Exception)
|
||||
{
|
||||
// the online localization failed so will default to local files
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
// culture doesn't exist so we just want language
|
||||
if (localizationFiles.Length == 0)
|
||||
{
|
||||
localizationFile = $"Localization{Path.DirectorySeparatorChar}IW4MAdmin.en-US.json";
|
||||
localizationContents = File.ReadAllText(localizationFile);
|
||||
localizationFiles = Directory.GetFiles(Path.Join(Utilities.OperatingDirectory, "Localization"), $"*.{currentLocale.Substring(0, 2)}*.json");
|
||||
}
|
||||
|
||||
Utilities.CurrentLocalization = Newtonsoft.Json.JsonConvert.DeserializeObject<SharedLibraryCore.Localization.Layout>(localizationContents);
|
||||
// language doesn't exist either so defaulting to english
|
||||
if (localizationFiles.Length == 0)
|
||||
{
|
||||
localizationFiles = Directory.GetFiles(Path.Join(Utilities.OperatingDirectory, "Localization"), "*.en-US.json");
|
||||
}
|
||||
|
||||
// this should never happen unless the localization folder is empty
|
||||
if (localizationFiles.Length == 0)
|
||||
{
|
||||
throw new Exception("No localization files were found");
|
||||
}
|
||||
|
||||
var localizationDict = new Dictionary<string, string>();
|
||||
|
||||
foreach (string filePath in localizationFiles)
|
||||
{
|
||||
var localizationContents = File.ReadAllText(filePath, Encoding.UTF8);
|
||||
var eachLocalizationFile = Newtonsoft.Json.JsonConvert.DeserializeObject<SharedLibraryCore.Localization.Layout>(localizationContents);
|
||||
|
||||
foreach (var item in eachLocalizationFile.LocalizationIndex.Set)
|
||||
{
|
||||
if (!localizationDict.TryAdd(item.Key, item.Value))
|
||||
{
|
||||
Program.ServerManager.GetLogger(0).WriteError($"Could not add locale string {item.Key} to localization");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string localizationFile = $"{Path.Join(Utilities.OperatingDirectory, "Localization")}{Path.DirectorySeparatorChar}IW4MAdmin.{currentLocale}-{currentLocale.ToUpper()}.json";
|
||||
|
||||
Utilities.CurrentLocalization = new SharedLibraryCore.Localization.Layout(localizationDict)
|
||||
{
|
||||
LocalizationName = currentLocale,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,109 +0,0 @@
|
||||
{
|
||||
"LocalizationName": "en-US",
|
||||
"LocalizationSet": {
|
||||
"MANAGER_VERSION_FAIL": "Could not get latest IW4MAdmin version",
|
||||
"MANAGER_VERSION_UPDATE": "has an update. Latest version is",
|
||||
"MANAGER_VERSION_CURRENT": "Your version is",
|
||||
"MANAGER_VERSION_SUCCESS": "IW4MAdmin is up to date",
|
||||
"MANAGER_INIT_FAIL": "Fatal error during initialization",
|
||||
"MANAGER_EXIT": "Press any key to exit...",
|
||||
"SETUP_ENABLE_WEBFRONT": "Enable webfront",
|
||||
"SETUP_ENABLE_MULTIOWN": "Enable multiple owners",
|
||||
"SETUP_ENABLE_STEPPEDPRIV": "Enable stepped privilege hierarchy",
|
||||
"SETUP_ENABLE_CUSTOMSAY": "Enable custom say name",
|
||||
"SETUP_SAY_NAME": "Enter custom say name",
|
||||
"SETUP_USE_CUSTOMENCODING": "Use custom encoding parser",
|
||||
"SETUP_ENCODING_STRING": "Enter encoding string",
|
||||
"SETUP_ENABLE_VPNS": "Enable client VPNs",
|
||||
"SETUP_IPHUB_KEY": "Enter iphub.info api key",
|
||||
"SETUP_DISPLAY_DISCORD": "Display discord link on webfront",
|
||||
"SETUP_DISCORD_INVITE": "Enter discord invite link",
|
||||
"SETUP_SERVER_USET6M": "Use T6M parser",
|
||||
"SETUP_SERVER_IP": "Enter server IP Address",
|
||||
"SETUP_SERVER_PORT": "Enter server port",
|
||||
"SETUP_SERVER_RCON": "Enter server RCon password",
|
||||
"SETUP_SERVER_SAVE": "Configuration saved, add another",
|
||||
"SERVER_KICK_VPNS_NOTALLOWED": "VPNs are not allowed on this server",
|
||||
"SERVER_KICK_TEXT": "You were kicked",
|
||||
"SERVER_KICK_MINNAME": "Your name must contain at least 3 characters",
|
||||
"SERVER_KICK_NAME_INUSE": "Your name is being used by someone else",
|
||||
"SERVER_KICK_GENERICNAME": "Please change your name using /name",
|
||||
"SERVER_KICK_CONTROLCHARS": "Your name cannot contain control characters",
|
||||
"SERVER_TB_TEXT": "You're temporarily banned",
|
||||
"SERVER_TB_REMAIN": "You are temporarily banned",
|
||||
"SERVER_BAN_TEXT": "You're banned",
|
||||
"SERVER_BAN_PREV": "Previously banned for",
|
||||
"SERVER_BAN_APPEAL": "appeal at",
|
||||
"SERVER_REPORT_COUNT": "There are ^5{0} ^7recent reports",
|
||||
"SERVER_WARNLIMT_REACHED": "Too many warnings",
|
||||
"SERVER_WARNING": "Warning",
|
||||
"SERVER_WEBSITE_GENERIC": "this server's website",
|
||||
"BROADCAST_ONLINE": "^5IW4MADMIN ^7is now ^2ONLINE",
|
||||
"BROADCAST_OFFLINE": "IW4MAdmin is going offline",
|
||||
"COMMAND_HELP_SYNTAX": "syntax:",
|
||||
"COMMAND_HELP_OPTIONAL": "optional",
|
||||
"COMMAND_UNKNOWN": "You entered an unknown command",
|
||||
"COMMAND_NOACCESS": "You do not have access to that command",
|
||||
"COMMAND_NOTAUTHORIZED": "You are not authorized to execute that command",
|
||||
"COMMAND_MISSINGARGS": "Not enough arguments supplied",
|
||||
"COMMAND_TARGET_MULTI": "Multiple players match that name",
|
||||
"COMMAND_TARGET_NOTFOUND": "Unable to find specified player",
|
||||
"PLUGIN_IMPORTER_NOTFOUND": "No plugins found to load",
|
||||
"PLUGIN_IMPORTER_REGISTERCMD": "Registered command",
|
||||
"COMMANDS_OWNER_SUCCESS": "Congratulations, you have claimed ownership of this server!",
|
||||
"COMMANDS_OWNER_FAIL": "This server already has an owner",
|
||||
"COMMANDS_WARN_FAIL": "You do not have the required privileges to warn",
|
||||
"COMMANDS_WARNCLEAR_SUCCESS": "All warning cleared for",
|
||||
"COMMANDS_KICK_SUCCESS": "has been kicked",
|
||||
"COMMANDS_KICK_FAIL": "You do not have the required privileges to kick",
|
||||
"COMMANDS_TEMPBAN_SUCCESS": "has been temporarily banned for",
|
||||
"COMMANDS_TEMPBAN_FAIL": "You cannot temporarily ban",
|
||||
"COMMANDS_BAN_SUCCESS": "has been permanently banned",
|
||||
"COMMANDS_BAN_FAIL": "You cannot ban",
|
||||
"COMMANDS_UNBAN_SUCCESS": "Successfully unbanned",
|
||||
"COMMANDS_UNBAN_FAIL": "is not banned",
|
||||
"COMMANDS_HELP_NOTFOUND": "Could not find that command",
|
||||
"COMMANDS_HELP_MOREINFO": "Type !help <command name> to get command usage syntax",
|
||||
"COMMANDS_FASTRESTART_UNMASKED": "fast restarted the map",
|
||||
"COMMANDS_FASTRESTART_MASKED": "The map has been fast restarted",
|
||||
"COMMANDS_MAPROTATE": "Map rotating in ^55 ^7seconds",
|
||||
"COMMANDS_SETLEVEL_SELF": "You cannot change your own level",
|
||||
"COMMANDS_SETLEVEL_OWNER": "There can only be 1 owner. Modify your settings if multiple owners are required",
|
||||
"COMMANDS_SETLEVEL_STEPPEDDISABLED": "This server does not allow you to promote",
|
||||
"COMMANDS_SETLEVEL_LEVELTOOHIGH": "You can only promote ^5{0} ^7to ^5{1} ^7or lower privilege",
|
||||
"COMMANDS_SETLEVEL_SUCCESS_TARGET": "Congratulations! You have been promoted to",
|
||||
"COMMANDS_SETLEVEL_SUCCESS": "was successfully promoted",
|
||||
"COMMANDS_SETLEVEL_FAIL": "Invalid group specified",
|
||||
"COMMANDS_ADMINS_NONE": "No visible administrators online",
|
||||
"COMMANDS_MAP_SUCCESS": "Changing to map",
|
||||
"COMMANDS_MAP_UKN": "Attempting to change to unknown map",
|
||||
"COMMANDS_FIND_MIN": "Please enter at least 3 characters",
|
||||
"COMMANDS_FIND_EMPTY": "No players found",
|
||||
"COMMANDS_RULES_NONE": "The server owner has not set any rules",
|
||||
"COMMANDS_FLAG_SUCCESS": "You have flagged",
|
||||
"COMMANDS_FLAG_UNFLAG": "You have unflagged",
|
||||
"COMMANDS_FLAG_FAIL": "You cannot flag",
|
||||
"COMMANDS_REPORT_FAIL_CAMP": "You cannot report an player for camping",
|
||||
"COMMANDS_REPORT_FAIL_DUPLICATE": "You have already reported this player",
|
||||
"COMMANDS_REPORT_FAIL_SELF": "You cannot report yourself",
|
||||
"COMMANDS_REPORT_FAIL": "You cannot report",
|
||||
"COMMANDS_REPORT_SUCCESS": "Thank you for your report, an administrator has been notified",
|
||||
"COMMANDS_REPORTS_CLEAR_SUCCESS": "Reports successfully cleared",
|
||||
"COMMANDS_REPORTS_NONE": "No players reported yet",
|
||||
"COMMANDS_MASK_ON": "You are now masked",
|
||||
"COMMANDS_MASK_OFF": "You are now unmasked",
|
||||
"COMMANDS_BANINFO_NONE": "No active ban was found for that player",
|
||||
"COMMANDS_BANINO_SUCCESS": "was banned by ^5{0} ^7for:",
|
||||
"COMMANDS_ALIAS_ALIASES": "Aliases",
|
||||
"COMMANDS_ALIAS_IPS": "IPs",
|
||||
"COMMANDS_RCON_SUCCESS": "Successfully sent RCon command",
|
||||
"COMMANDS_PLUGINS_LOADED": "Loaded Plugins",
|
||||
"COMMANDS_IP_SUCCESS": "Your external IP is",
|
||||
"COMMANDS_PRUNE_FAIL": "Invalid number of inactive days",
|
||||
"COMMANDS_PRUNE_SUCCESS": "inactive privileged users were pruned",
|
||||
"COMMANDS_PASSWORD_FAIL": "Your password must be at least 5 characters long",
|
||||
"COMMANDS_PASSWORD_SUCCESS": "Your password has been set successfully",
|
||||
"COMMANDS_PING_TARGET": "ping is",
|
||||
"COMMANDS_PING_SELF": "Your ping is"
|
||||
}
|
||||
}
|
@ -1,79 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
class Logger : SharedLibraryCore.Interfaces.ILogger
|
||||
{
|
||||
enum LogType
|
||||
{
|
||||
Verbose,
|
||||
Info,
|
||||
Debug,
|
||||
Warning,
|
||||
Error,
|
||||
Assert
|
||||
}
|
||||
|
||||
string FileName;
|
||||
object ThreadLock;
|
||||
|
||||
public Logger(string fn)
|
||||
{
|
||||
FileName = fn;
|
||||
ThreadLock = new object();
|
||||
if (File.Exists(fn))
|
||||
File.Delete(fn);
|
||||
}
|
||||
|
||||
void Write(string msg, LogType type)
|
||||
{
|
||||
string LogLine = $"[{DateTime.Now.ToString("HH:mm:ss")}] - {type}: {msg}";
|
||||
lock (ThreadLock)
|
||||
{
|
||||
#if DEBUG
|
||||
// lets keep it simple and dispose of everything quickly as logging wont be that much (relatively)
|
||||
|
||||
Console.WriteLine(LogLine);
|
||||
File.AppendAllText(FileName, LogLine + Environment.NewLine);
|
||||
#else
|
||||
if (type == LogType.Error || type == LogType.Verbose)
|
||||
Console.WriteLine(LogLine);
|
||||
//if (type != LogType.Debug)
|
||||
File.AppendAllText(FileName, $"{LogLine}{Environment.NewLine}");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
public void WriteVerbose(string msg)
|
||||
{
|
||||
Write(msg, LogType.Verbose);
|
||||
}
|
||||
|
||||
public void WriteDebug(string msg)
|
||||
{
|
||||
Write(msg, LogType.Debug);
|
||||
}
|
||||
|
||||
public void WriteError(string msg)
|
||||
{
|
||||
Write(msg, LogType.Error);
|
||||
}
|
||||
|
||||
public void WriteInfo(string msg)
|
||||
{
|
||||
Write(msg, LogType.Info);
|
||||
}
|
||||
|
||||
public void WriteWarning(string msg)
|
||||
{
|
||||
Write(msg, LogType.Warning);
|
||||
}
|
||||
|
||||
public void WriteAssert(bool condition, string msg)
|
||||
{
|
||||
if (!condition)
|
||||
Write(msg, LogType.Assert);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,45 +1,63 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
using IW4MAdmin.Application.Migration;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Objects;
|
||||
using SharedLibraryCore.Database;
|
||||
using SharedLibraryCore.Localization;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
public class Program
|
||||
{
|
||||
static public double Version { get; private set; }
|
||||
static public ApplicationManager ServerManager = ApplicationManager.GetInstance();
|
||||
public static string OperatingDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + Path.DirectorySeparatorChar;
|
||||
static public ApplicationManager ServerManager;
|
||||
private static ManualResetEventSlim OnShutdownComplete = new ManualResetEventSlim();
|
||||
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
AppDomain.CurrentDomain.SetData("DataDirectory", OperatingDirectory);
|
||||
System.Diagnostics.Process.GetCurrentProcess().PriorityClass = System.Diagnostics.ProcessPriorityClass.BelowNormal;
|
||||
Localization.Configure.Initialize();
|
||||
var loc = Utilities.CurrentLocalization.LocalizationSet;
|
||||
AppDomain.CurrentDomain.SetData("DataDirectory", Utilities.OperatingDirectory);
|
||||
Console.OutputEncoding = Encoding.UTF8;
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
|
||||
Version = Assembly.GetExecutingAssembly().GetName().Version.Major + Assembly.GetExecutingAssembly().GetName().Version.Minor / 10.0f;
|
||||
Version = Utilities.GetVersionAsDouble();
|
||||
|
||||
Console.WriteLine("=====================================================");
|
||||
Console.WriteLine(" IW4M ADMIN");
|
||||
Console.WriteLine(" by RaidMax ");
|
||||
Console.WriteLine($" Version {Version.ToString("0.0")}");
|
||||
Console.WriteLine($" Version {Utilities.GetVersionAsString()}");
|
||||
Console.WriteLine("=====================================================");
|
||||
|
||||
Index loc = null;
|
||||
|
||||
try
|
||||
{
|
||||
using (var db = new DatabaseContext())
|
||||
new ContextSeed(db).Seed().Wait();
|
||||
ServerManager = ApplicationManager.GetInstance();
|
||||
var configuration = ServerManager.GetApplicationSettings().Configuration();
|
||||
|
||||
if (configuration != null)
|
||||
{
|
||||
Localization.Configure.Initialize(configuration.EnableCustomLocale ? (configuration.CustomLocale ?? "windows-1252") : "windows-1252");
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
Localization.Configure.Initialize();
|
||||
}
|
||||
|
||||
loc = Utilities.CurrentLocalization.LocalizationIndex;
|
||||
Console.CancelKeyPress += new ConsoleCancelEventHandler(OnCancelKey);
|
||||
|
||||
CheckDirectories();
|
||||
// do any needed migrations
|
||||
// todo: move out
|
||||
ConfigurationMigration.MoveConfigFolder10518(null);
|
||||
|
||||
ServerManager = ApplicationManager.GetInstance();
|
||||
ServerManager.Logger.WriteInfo($"Version is {Version}");
|
||||
|
||||
var api = API.Master.Endpoint.Get();
|
||||
|
||||
var version = new API.Master.VersionInfo()
|
||||
{
|
||||
CurrentVersionStable = 99.99f
|
||||
@ -65,7 +83,7 @@ namespace IW4MAdmin.Application
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine(loc["MANAGER_VERSION_FAIL"]);
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
}
|
||||
|
||||
#if !PRERELEASE
|
||||
@ -73,82 +91,115 @@ namespace IW4MAdmin.Application
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.DarkYellow;
|
||||
Console.WriteLine($"IW4MAdmin {loc["MANAGER_VERSION_UPDATE"]} [v{version.CurrentVersionStable.ToString("0.0")}]");
|
||||
Console.WriteLine($"{loc["MANAGER_VERSION_CURRENT"]} [v{Version.ToString("0.0")}]");
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.WriteLine(loc["MANAGER_VERSION_CURRENT"].FormatExt($"[v{Version.ToString("0.0")}]"));
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
}
|
||||
#else
|
||||
else if (version.CurrentVersionPrerelease > Version)
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.DarkYellow;
|
||||
Console.WriteLine($"IW4MAdmin-Prerelease {loc["MANAGER_VERSION_UPDATE"]} [v{version.CurrentVersionPrerelease.ToString("0.0")}-pr]");
|
||||
Console.WriteLine($"{loc["MANAGER_VERSION_CURRENT"]} [v{Version.ToString("0.0")}-pr]");
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.WriteLine(loc["MANAGER_VERSION_CURRENT"].FormatExt($"[v{Version.ToString("0.0")}-pr]"));
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
}
|
||||
#endif
|
||||
else
|
||||
{
|
||||
Console.ForegroundColor = ConsoleColor.Green;
|
||||
Console.WriteLine(loc["MANAGER_VERSION_SUCCESS"]);
|
||||
Console.ForegroundColor = ConsoleColor.White;
|
||||
Console.ForegroundColor = ConsoleColor.Gray;
|
||||
}
|
||||
|
||||
ServerManager.Init().Wait();
|
||||
|
||||
var consoleTask = Task.Run(() =>
|
||||
var consoleTask = Task.Run(async () =>
|
||||
{
|
||||
String userInput;
|
||||
Player Origin = ServerManager.GetClientService().Get(1).Result.AsPlayer();
|
||||
string userInput;
|
||||
var Origin = Utilities.IW4MAdminClient(ServerManager.Servers[0]);
|
||||
|
||||
do
|
||||
{
|
||||
userInput = Console.ReadLine();
|
||||
|
||||
if (userInput?.ToLower() == "quit")
|
||||
{
|
||||
ServerManager.Stop();
|
||||
}
|
||||
|
||||
if (ServerManager.Servers.Count == 0)
|
||||
{
|
||||
Console.WriteLine("No servers are currently being monitored");
|
||||
Console.WriteLine(loc["MANAGER_CONSOLE_NOSERV"]);
|
||||
continue;
|
||||
}
|
||||
|
||||
Origin.CurrentServer = ServerManager.Servers[0];
|
||||
GameEvent E = new GameEvent(GameEvent.EventType.Say, userInput, Origin, null, ServerManager.Servers[0]);
|
||||
ServerManager.Servers[0].ExecuteEvent(E);
|
||||
if (userInput?.Length > 0)
|
||||
{
|
||||
GameEvent E = new GameEvent()
|
||||
{
|
||||
Type = GameEvent.EventType.Command,
|
||||
Data = userInput,
|
||||
Origin = Origin,
|
||||
Owner = ServerManager.Servers[0]
|
||||
};
|
||||
|
||||
ServerManager.GetEventHandler().AddEvent(E);
|
||||
await E.WaitAsync(30 * 1000);
|
||||
}
|
||||
Console.Write('>');
|
||||
|
||||
} while (ServerManager.Running);
|
||||
});
|
||||
|
||||
if (ServerManager.GetApplicationSettings().Configuration().EnableWebFront)
|
||||
{
|
||||
Task.Run(() => WebfrontCore.Program.Init(ServerManager));
|
||||
}
|
||||
|
||||
ServerManager.Start();
|
||||
ServerManager.Logger.WriteVerbose("Shutdown complete");
|
||||
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(loc["MANAGER_INIT_FAIL"]);
|
||||
string failMessage = loc == null ? "Failed to initalize IW4MAdmin" : loc["MANAGER_INIT_FAIL"];
|
||||
string exitMessage = loc == null ? "Press any key to exit..." : loc["MANAGER_EXIT"];
|
||||
|
||||
Console.WriteLine(failMessage);
|
||||
while (e.InnerException != null)
|
||||
{
|
||||
e = e.InnerException;
|
||||
}
|
||||
Console.WriteLine($"Exception: {e.Message}");
|
||||
Console.WriteLine(loc["MANAGER_EXIT"]);
|
||||
Console.WriteLine(e.Message);
|
||||
Console.WriteLine(exitMessage);
|
||||
Console.ReadKey();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ServerManager.GetApplicationSettings().Configuration().EnableWebFront)
|
||||
{
|
||||
Task.Run(() => WebfrontCore.Program.Init(ServerManager));
|
||||
}
|
||||
|
||||
OnShutdownComplete.Reset();
|
||||
ServerManager.Start();
|
||||
ServerManager.Logger.WriteVerbose(loc["MANAGER_SHUTDOWN_SUCCESS"]);
|
||||
OnShutdownComplete.Set();
|
||||
}
|
||||
|
||||
private static void OnCancelKey(object sender, ConsoleCancelEventArgs e)
|
||||
{
|
||||
ServerManager.Stop();
|
||||
OnShutdownComplete.Wait();
|
||||
}
|
||||
|
||||
static void CheckDirectories()
|
||||
{
|
||||
string curDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + Path.DirectorySeparatorChar;
|
||||
if (!Directory.Exists(Path.Join(Utilities.OperatingDirectory, "Plugins")))
|
||||
{
|
||||
Directory.CreateDirectory(Path.Join(Utilities.OperatingDirectory, "Plugins"));
|
||||
}
|
||||
|
||||
if (!Directory.Exists($"{curDirectory}Plugins"))
|
||||
Directory.CreateDirectory($"{curDirectory}Plugins");
|
||||
if (!Directory.Exists(Path.Join(Utilities.OperatingDirectory, "Database")))
|
||||
{
|
||||
Directory.CreateDirectory(Path.Join(Utilities.OperatingDirectory, "Database"));
|
||||
}
|
||||
|
||||
if (!Directory.Exists(Path.Join(Utilities.OperatingDirectory, "Log")))
|
||||
{
|
||||
Directory.CreateDirectory(Path.Join(Utilities.OperatingDirectory, "Log"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,415 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Commands;
|
||||
using SharedLibraryCore.Helpers;
|
||||
using SharedLibraryCore.Exceptions;
|
||||
using SharedLibraryCore.Objects;
|
||||
using SharedLibraryCore.Services;
|
||||
using IW4MAdmin.Application.API;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using WebfrontCore;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
public class ApplicationManager : IManager
|
||||
{
|
||||
private List<Server> _servers;
|
||||
public List<Server> Servers => _servers.OrderByDescending(s => s.ClientNum).ToList();
|
||||
public Dictionary<int, Player> PrivilegedClients { get; set; }
|
||||
public ILogger Logger { get; private set; }
|
||||
public bool Running { get; private set; }
|
||||
public EventHandler<GameEvent> ServerEventOccurred { get; private set; }
|
||||
public DateTime StartTime { get; private set; }
|
||||
|
||||
static ApplicationManager Instance;
|
||||
List<AsyncStatus> TaskStatuses;
|
||||
List<Command> Commands;
|
||||
List<MessageToken> MessageTokens;
|
||||
ClientService ClientSvc;
|
||||
AliasService AliasSvc;
|
||||
PenaltyService PenaltySvc;
|
||||
BaseConfigurationHandler<ApplicationConfiguration> ConfigHandler;
|
||||
EventApi Api;
|
||||
#if FTP_LOG
|
||||
const int UPDATE_FREQUENCY = 700;
|
||||
#else
|
||||
const int UPDATE_FREQUENCY = 450;
|
||||
#endif
|
||||
|
||||
private ApplicationManager()
|
||||
{
|
||||
Logger = new Logger($@"{Utilities.OperatingDirectory}IW4MAdmin.log");
|
||||
_servers = new List<Server>();
|
||||
Commands = new List<Command>();
|
||||
TaskStatuses = new List<AsyncStatus>();
|
||||
MessageTokens = new List<MessageToken>();
|
||||
ClientSvc = new ClientService();
|
||||
AliasSvc = new AliasService();
|
||||
PenaltySvc = new PenaltyService();
|
||||
PrivilegedClients = new Dictionary<int, Player>();
|
||||
Api = new EventApi();
|
||||
ServerEventOccurred += Api.OnServerEvent;
|
||||
ConfigHandler = new BaseConfigurationHandler<ApplicationConfiguration>("IW4MAdminSettings");
|
||||
Console.CancelKeyPress += new ConsoleCancelEventHandler(OnCancelKey);
|
||||
StartTime = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
private void OnCancelKey(object sender, ConsoleCancelEventArgs args)
|
||||
{
|
||||
Stop();
|
||||
}
|
||||
|
||||
|
||||
public IList<Server> GetServers()
|
||||
{
|
||||
return Servers;
|
||||
}
|
||||
|
||||
public IList<Command> GetCommands()
|
||||
{
|
||||
return Commands;
|
||||
}
|
||||
|
||||
public static ApplicationManager GetInstance()
|
||||
{
|
||||
return Instance ?? (Instance = new ApplicationManager());
|
||||
}
|
||||
|
||||
public async Task Init()
|
||||
{
|
||||
#region DATABASE
|
||||
var ipList = (await ClientSvc.Find(c => c.Level > Player.Permission.Trusted))
|
||||
.Select(c => new
|
||||
{
|
||||
c.Password,
|
||||
c.PasswordSalt,
|
||||
c.ClientId,
|
||||
c.Level,
|
||||
c.Name
|
||||
});
|
||||
|
||||
foreach (var a in ipList)
|
||||
{
|
||||
try
|
||||
{
|
||||
PrivilegedClients.Add(a.ClientId, new Player()
|
||||
{
|
||||
Name = a.Name,
|
||||
ClientId = a.ClientId,
|
||||
Level = a.Level,
|
||||
PasswordSalt = a.PasswordSalt,
|
||||
Password = a.Password
|
||||
});
|
||||
}
|
||||
|
||||
catch (ArgumentException)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region CONFIG
|
||||
var config = ConfigHandler.Configuration();
|
||||
|
||||
// copy over default config if it doesn't exist
|
||||
if (config == null)
|
||||
{
|
||||
var defaultConfig = new BaseConfigurationHandler<DefaultConfiguration>("DefaultSettings").Configuration();
|
||||
ConfigHandler.Set((ApplicationConfiguration)new ApplicationConfiguration().Generate());
|
||||
var newConfig = ConfigHandler.Configuration();
|
||||
|
||||
newConfig.AutoMessagePeriod = defaultConfig.AutoMessagePeriod;
|
||||
newConfig.AutoMessages = defaultConfig.AutoMessages;
|
||||
newConfig.GlobalRules = defaultConfig.GlobalRules;
|
||||
newConfig.Maps = defaultConfig.Maps;
|
||||
|
||||
if (newConfig.Servers == null)
|
||||
{
|
||||
ConfigHandler.Set(newConfig);
|
||||
newConfig.Servers = ConfigurationGenerator.GenerateServerConfig(new List<ServerConfiguration>());
|
||||
config = newConfig;
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
}
|
||||
|
||||
else if (config != null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(config.Id))
|
||||
{
|
||||
config.Id = Guid.NewGuid().ToString();
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(config.WebfrontBindUrl))
|
||||
{
|
||||
config.WebfrontBindUrl = "http://127.0.0.1:1624";
|
||||
await ConfigHandler.Save();
|
||||
}
|
||||
}
|
||||
|
||||
else if (config.Servers.Count == 0)
|
||||
throw new ServerException("A server configuration in IW4MAdminSettings.json is invalid");
|
||||
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
Utilities.EncodingType = Encoding.GetEncoding(!string.IsNullOrEmpty(config.CustomParserEncoding) ? config.CustomParserEncoding : "windows-1252");
|
||||
|
||||
#endregion
|
||||
#region PLUGINS
|
||||
SharedLibraryCore.Plugins.PluginImporter.Load(this);
|
||||
|
||||
foreach (var Plugin in SharedLibraryCore.Plugins.PluginImporter.ActivePlugins)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Plugin.OnLoadAsync(this);
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.WriteError($"An error occured loading plugin {Plugin.Name}");
|
||||
Logger.WriteDebug($"Exception: {e.Message}");
|
||||
Logger.WriteDebug($"Stack Trace: {e.StackTrace}");
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region COMMANDS
|
||||
if (ClientSvc.GetOwners().Result.Count == 0)
|
||||
Commands.Add(new COwner());
|
||||
|
||||
Commands.Add(new CQuit());
|
||||
Commands.Add(new CKick());
|
||||
Commands.Add(new CSay());
|
||||
Commands.Add(new CTempBan());
|
||||
Commands.Add(new CBan());
|
||||
Commands.Add(new CWhoAmI());
|
||||
Commands.Add(new CList());
|
||||
Commands.Add(new CHelp());
|
||||
Commands.Add(new CFastRestart());
|
||||
Commands.Add(new CMapRotate());
|
||||
Commands.Add(new CSetLevel());
|
||||
Commands.Add(new CUsage());
|
||||
Commands.Add(new CUptime());
|
||||
Commands.Add(new CWarn());
|
||||
Commands.Add(new CWarnClear());
|
||||
Commands.Add(new CUnban());
|
||||
Commands.Add(new CListAdmins());
|
||||
Commands.Add(new CLoadMap());
|
||||
Commands.Add(new CFindPlayer());
|
||||
Commands.Add(new CListRules());
|
||||
Commands.Add(new CPrivateMessage());
|
||||
Commands.Add(new CFlag());
|
||||
Commands.Add(new CReport());
|
||||
Commands.Add(new CListReports());
|
||||
Commands.Add(new CListBanInfo());
|
||||
Commands.Add(new CListAlias());
|
||||
Commands.Add(new CExecuteRCON());
|
||||
Commands.Add(new CPlugins());
|
||||
Commands.Add(new CIP());
|
||||
Commands.Add(new CMask());
|
||||
Commands.Add(new CPruneAdmins());
|
||||
Commands.Add(new CKillServer());
|
||||
Commands.Add(new CSetPassword());
|
||||
Commands.Add(new CPing());
|
||||
|
||||
foreach (Command C in SharedLibraryCore.Plugins.PluginImporter.ActiveCommands)
|
||||
Commands.Add(C);
|
||||
#endregion
|
||||
|
||||
#region INIT
|
||||
async Task Init(ServerConfiguration Conf)
|
||||
{
|
||||
try
|
||||
{
|
||||
var ServerInstance = new IW4MServer(this, Conf);
|
||||
await ServerInstance.Initialize();
|
||||
|
||||
lock (_servers)
|
||||
{
|
||||
_servers.Add(ServerInstance);
|
||||
}
|
||||
|
||||
Logger.WriteVerbose($"Now monitoring {ServerInstance.Hostname}");
|
||||
|
||||
// this way we can keep track of execution time and see if problems arise.
|
||||
var Status = new AsyncStatus(ServerInstance, UPDATE_FREQUENCY);
|
||||
lock (TaskStatuses)
|
||||
{
|
||||
TaskStatuses.Add(Status);
|
||||
}
|
||||
}
|
||||
|
||||
catch (ServerException e)
|
||||
{
|
||||
Logger.WriteError($"Not monitoring server {Conf.IPAddress}:{Conf.Port} due to uncorrectable errors");
|
||||
if (e.GetType() == typeof(DvarException))
|
||||
Logger.WriteDebug($"Could not get the dvar value for {(e as DvarException).Data["dvar_name"]} (ensure the server has a map loaded)");
|
||||
else if (e.GetType() == typeof(NetworkException))
|
||||
{
|
||||
Logger.WriteDebug(e.Message);
|
||||
}
|
||||
|
||||
// throw the exception to the main method to stop before instantly exiting
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(config.Servers.Select(c => Init(c)).ToArray());
|
||||
|
||||
#endregion
|
||||
|
||||
Running = true;
|
||||
}
|
||||
|
||||
private void HeartBeatThread()
|
||||
{
|
||||
bool successfulConnection = false;
|
||||
restartConnection:
|
||||
while (!successfulConnection)
|
||||
{
|
||||
try
|
||||
{
|
||||
API.Master.Heartbeat.Send(this, true).Wait();
|
||||
successfulConnection = true;
|
||||
}
|
||||
|
||||
catch (Exception e)
|
||||
{
|
||||
successfulConnection = false;
|
||||
Logger.WriteWarning($"Could not connect to heartbeat server - {e.Message}");
|
||||
}
|
||||
|
||||
Thread.Sleep(30000);
|
||||
}
|
||||
|
||||
while (Running)
|
||||
{
|
||||
Logger.WriteDebug("Sending heartbeat...");
|
||||
try
|
||||
{
|
||||
API.Master.Heartbeat.Send(this).Wait();
|
||||
}
|
||||
catch (System.Net.Http.HttpRequestException e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
}
|
||||
|
||||
catch (AggregateException e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
var exceptions = e.InnerExceptions.Where(ex => ex.GetType() == typeof(RestEase.ApiException));
|
||||
|
||||
foreach (var ex in exceptions)
|
||||
{
|
||||
if (((RestEase.ApiException)ex).StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
successfulConnection = false;
|
||||
goto restartConnection;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
catch (RestEase.ApiException e)
|
||||
{
|
||||
Logger.WriteWarning($"Could not send heartbeat - {e.Message}");
|
||||
if (e.StatusCode == System.Net.HttpStatusCode.Unauthorized)
|
||||
{
|
||||
successfulConnection = false;
|
||||
goto restartConnection;
|
||||
}
|
||||
}
|
||||
|
||||
Thread.Sleep(30000);
|
||||
}
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
Task.Run(() => HeartBeatThread());
|
||||
while (Running || TaskStatuses.Count > 0)
|
||||
{
|
||||
for (int i = 0; i < TaskStatuses.Count; i++)
|
||||
{
|
||||
var Status = TaskStatuses[i];
|
||||
|
||||
// task is read to be rerun
|
||||
if (Status.RequestedTask == null || Status.RequestedTask.Status == TaskStatus.RanToCompletion)
|
||||
{
|
||||
// remove the task when we want to quit and last run has finished
|
||||
if (!Running)
|
||||
{
|
||||
TaskStatuses.RemoveAt(i);
|
||||
continue;
|
||||
}
|
||||
// normal operation
|
||||
else
|
||||
{
|
||||
Status.Update(new Task<bool>(() => { return (Status.Dependant as Server).ProcessUpdatesAsync(Status.GetToken()).Result; }));
|
||||
if (Status.RunAverage > 1000 + UPDATE_FREQUENCY && !(Status.Dependant as Server).Throttled)
|
||||
Logger.WriteWarning($"Update task average execution is longer than desired for {(Status.Dependant as Server)} [{Status.RunAverage}ms]");
|
||||
}
|
||||
}
|
||||
|
||||
if (Status.RequestedTask.Status == TaskStatus.Faulted)
|
||||
{
|
||||
Logger.WriteWarning($"Update task for {(Status.Dependant as Server)} faulted, restarting");
|
||||
Status.Abort();
|
||||
}
|
||||
}
|
||||
|
||||
Thread.Sleep(UPDATE_FREQUENCY);
|
||||
}
|
||||
#if !DEBUG
|
||||
foreach (var S in Servers)
|
||||
S.Broadcast(Utilities.CurrentLocalization.LocalizationSet["BROADCAST_OFFLINE"]).Wait();
|
||||
#endif
|
||||
_servers.Clear();
|
||||
}
|
||||
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
Running = false;
|
||||
}
|
||||
|
||||
public ILogger GetLogger()
|
||||
{
|
||||
return Logger;
|
||||
}
|
||||
|
||||
public IList<MessageToken> GetMessageTokens()
|
||||
{
|
||||
return MessageTokens;
|
||||
}
|
||||
|
||||
public IList<Player> GetActiveClients()
|
||||
{
|
||||
var ActiveClients = new List<Player>();
|
||||
|
||||
foreach (var server in _servers)
|
||||
ActiveClients.AddRange(server.Players.Where(p => p != null));
|
||||
|
||||
return ActiveClients;
|
||||
}
|
||||
|
||||
public ClientService GetClientService() => ClientSvc;
|
||||
public AliasService GetAliasService() => AliasSvc;
|
||||
public PenaltyService GetPenaltyService() => PenaltySvc;
|
||||
public IConfigurationHandler<ApplicationConfiguration> GetApplicationSettings() => ConfigHandler;
|
||||
public IDictionary<int, Player> GetPrivilegedClients() => PrivilegedClients;
|
||||
public IEventApi GetEventApi() => Api;
|
||||
public bool ShutdownRequested() => !Running;
|
||||
}
|
||||
}
|
69
Application/Migration/ConfigurationMigration.cs
Normal file
69
Application/Migration/ConfigurationMigration.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace IW4MAdmin.Application.Migration
|
||||
{
|
||||
/// <summary>
|
||||
/// helps facilitate the migration of configs from one version and or location
|
||||
/// to another
|
||||
/// </summary>
|
||||
class ConfigurationMigration
|
||||
{
|
||||
/// <summary>
|
||||
/// moves existing configs from the root folder into a configs folder
|
||||
/// </summary>
|
||||
public static void MoveConfigFolder10518(ILogger log)
|
||||
{
|
||||
string currentDirectory = Utilities.OperatingDirectory;
|
||||
|
||||
// we don't want to do this for migrations or tests where the
|
||||
// property isn't initialized or it's wrong
|
||||
if (currentDirectory != null)
|
||||
{
|
||||
string configDirectory = Path.Join(currentDirectory, "Configuration");
|
||||
|
||||
if (!Directory.Exists(configDirectory))
|
||||
{
|
||||
log?.WriteDebug($"Creating directory for configs {configDirectory}");
|
||||
Directory.CreateDirectory(configDirectory);
|
||||
}
|
||||
|
||||
var configurationFiles = Directory.EnumerateFiles(currentDirectory, "*.json")
|
||||
.Select(f => f.Split(Path.DirectorySeparatorChar).Last())
|
||||
.Where(f => f.Count(c => c == '.') == 1);
|
||||
|
||||
foreach (var configFile in configurationFiles)
|
||||
{
|
||||
log?.WriteDebug($"Moving config file {configFile}");
|
||||
string destinationPath = Path.Join("Configuration", configFile);
|
||||
if (!File.Exists(destinationPath))
|
||||
{
|
||||
File.Move(configFile, destinationPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (!File.Exists(Path.Join("Database", "Database.db")) &&
|
||||
File.Exists("Database.db"))
|
||||
{
|
||||
log?.WriteDebug("Moving database file");
|
||||
File.Move("Database.db", Path.Join("Database", "Database.db"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void ModifyLogPath020919(SharedLibraryCore.Configuration.ServerConfiguration config)
|
||||
{
|
||||
if (config.ManualLogPath.IsRemoteLog())
|
||||
{
|
||||
config.GameLogServerUrl = new Uri(config.ManualLogPath);
|
||||
config.ManualLogPath = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
124
Application/Misc/Logger.cs
Normal file
124
Application/Misc/Logger.cs
Normal file
@ -0,0 +1,124 @@
|
||||
using SharedLibraryCore;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
class Logger : SharedLibraryCore.Interfaces.ILogger
|
||||
{
|
||||
enum LogType
|
||||
{
|
||||
Verbose,
|
||||
Info,
|
||||
Debug,
|
||||
Warning,
|
||||
Error,
|
||||
Assert
|
||||
}
|
||||
|
||||
readonly string FileName;
|
||||
readonly SemaphoreSlim OnLogWriting;
|
||||
static readonly short MAX_LOG_FILES = 10;
|
||||
|
||||
public Logger(string fn)
|
||||
{
|
||||
FileName = Path.Join(Utilities.OperatingDirectory, "Log", $"{fn}.log");
|
||||
OnLogWriting = new SemaphoreSlim(1, 1);
|
||||
RotateLogs();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// rotates logs when log is initialized
|
||||
/// </summary>
|
||||
private void RotateLogs()
|
||||
{
|
||||
string maxLog = FileName + MAX_LOG_FILES;
|
||||
|
||||
if (File.Exists(maxLog))
|
||||
{
|
||||
File.Delete(maxLog);
|
||||
}
|
||||
|
||||
for (int i = MAX_LOG_FILES - 1; i >= 0; i--)
|
||||
{
|
||||
string logToMove = i == 0 ? FileName : FileName + i;
|
||||
string movedLogName = FileName + (i + 1);
|
||||
|
||||
if (File.Exists(logToMove))
|
||||
{
|
||||
File.Move(logToMove, movedLogName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Write(string msg, LogType type)
|
||||
{
|
||||
OnLogWriting.Wait();
|
||||
|
||||
string stringType = type.ToString();
|
||||
|
||||
try
|
||||
{
|
||||
stringType = Utilities.CurrentLocalization.LocalizationIndex[$"GLOBAL_{type.ToString().ToUpper()}"];
|
||||
}
|
||||
|
||||
catch (Exception) { }
|
||||
|
||||
string LogLine = $"[{DateTime.Now.ToString("MM.dd.yyy HH:mm:ss.fff")}] - {stringType}: {msg}";
|
||||
try
|
||||
{
|
||||
#if DEBUG
|
||||
// lets keep it simple and dispose of everything quickly as logging wont be that much (relatively)
|
||||
Console.WriteLine(LogLine);
|
||||
File.AppendAllText(FileName, LogLine + Environment.NewLine);
|
||||
#else
|
||||
if (type == LogType.Error || type == LogType.Verbose)
|
||||
Console.WriteLine(LogLine);
|
||||
//if (type != LogType.Debug)
|
||||
File.AppendAllText(FileName, $"{LogLine}{Environment.NewLine}");
|
||||
#endif
|
||||
}
|
||||
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Well.. It looks like your machine can't event write to the log file. That's something else...");
|
||||
Console.WriteLine(ex.GetExceptionInfo());
|
||||
}
|
||||
|
||||
OnLogWriting.Release(1);
|
||||
}
|
||||
|
||||
public void WriteVerbose(string msg)
|
||||
{
|
||||
Write(msg, LogType.Verbose);
|
||||
}
|
||||
|
||||
public void WriteDebug(string msg)
|
||||
{
|
||||
Write(msg, LogType.Debug);
|
||||
}
|
||||
|
||||
public void WriteError(string msg)
|
||||
{
|
||||
Write(msg, LogType.Error);
|
||||
}
|
||||
|
||||
public void WriteInfo(string msg)
|
||||
{
|
||||
Write(msg, LogType.Info);
|
||||
}
|
||||
|
||||
public void WriteWarning(string msg)
|
||||
{
|
||||
Write(msg, LogType.Warning);
|
||||
}
|
||||
|
||||
public void WriteAssert(bool condition, string msg)
|
||||
{
|
||||
if (!condition)
|
||||
Write(msg, LogType.Assert);
|
||||
}
|
||||
}
|
||||
}
|
26
Application/Misc/PageList.cs
Normal file
26
Application/Misc/PageList.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace IW4MAdmin.Application
|
||||
{
|
||||
/// <summary>
|
||||
/// implementatin of IPageList that supports basic
|
||||
/// pages title and page location for webfront
|
||||
/// </summary>
|
||||
class PageList : IPageList
|
||||
{
|
||||
/// <summary>
|
||||
/// Pages dictionary
|
||||
/// Key = page name
|
||||
/// Value = page location (url)
|
||||
/// </summary>
|
||||
public IDictionary<string, string> Pages { get; set; }
|
||||
|
||||
public PageList()
|
||||
{
|
||||
Pages = new Dictionary<string, string>();
|
||||
}
|
||||
}
|
||||
}
|
100
Application/Misc/TokenAuthentication.cs
Normal file
100
Application/Misc/TokenAuthentication.cs
Normal file
@ -0,0 +1,100 @@
|
||||
using SharedLibraryCore.Helpers;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace IW4MAdmin.Application.Misc
|
||||
{
|
||||
class TokenAuthentication : ITokenAuthentication
|
||||
{
|
||||
private readonly ConcurrentDictionary<long, TokenState> _tokens;
|
||||
private readonly RNGCryptoServiceProvider _random;
|
||||
private readonly static TimeSpan _timeoutPeriod = new TimeSpan(0, 0, 120);
|
||||
private const short TOKEN_LENGTH = 4;
|
||||
|
||||
public TokenAuthentication()
|
||||
{
|
||||
_tokens = new ConcurrentDictionary<long, TokenState>();
|
||||
_random = new RNGCryptoServiceProvider();
|
||||
}
|
||||
|
||||
public bool AuthorizeToken(long networkId, string token)
|
||||
{
|
||||
bool authorizeSuccessful = _tokens.ContainsKey(networkId) && _tokens[networkId].Token == token;
|
||||
|
||||
if (authorizeSuccessful)
|
||||
{
|
||||
_tokens.TryRemove(networkId, out TokenState _);
|
||||
}
|
||||
|
||||
return authorizeSuccessful;
|
||||
}
|
||||
|
||||
public TokenState GenerateNextToken(long networkId)
|
||||
{
|
||||
TokenState state = null;
|
||||
|
||||
if (_tokens.ContainsKey(networkId))
|
||||
{
|
||||
state = _tokens[networkId];
|
||||
|
||||
if ((DateTime.Now - state.RequestTime) > _timeoutPeriod)
|
||||
{
|
||||
_tokens.TryRemove(networkId, out TokenState _);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
state = new TokenState()
|
||||
{
|
||||
NetworkId = networkId,
|
||||
Token = _generateToken(),
|
||||
TokenDuration = _timeoutPeriod
|
||||
};
|
||||
|
||||
_tokens.TryAdd(networkId, state);
|
||||
|
||||
// perform some housekeeping so we don't have built up tokens if they're not ever used
|
||||
foreach (var (key, value) in _tokens)
|
||||
{
|
||||
if ((DateTime.Now - value.RequestTime) > _timeoutPeriod)
|
||||
{
|
||||
_tokens.TryRemove(key, out TokenState _);
|
||||
}
|
||||
}
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
public string _generateToken()
|
||||
{
|
||||
bool validCharacter(char c)
|
||||
{
|
||||
// this ensure that the characters are 0-9, A-Z, a-z
|
||||
return (c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123);
|
||||
}
|
||||
|
||||
StringBuilder token = new StringBuilder();
|
||||
|
||||
while (token.Length < TOKEN_LENGTH)
|
||||
{
|
||||
byte[] charSet = new byte[1];
|
||||
_random.GetBytes(charSet);
|
||||
|
||||
if (validCharacter((char)charSet[0]))
|
||||
{
|
||||
token.Append((char)charSet[0]);
|
||||
}
|
||||
}
|
||||
|
||||
_random.Dispose();
|
||||
return token.ToString();
|
||||
}
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Application.Misc
|
||||
{
|
||||
public class VPNCheck
|
||||
{
|
||||
public static async Task<bool> UsingVPN(string ip, string apiKey)
|
||||
{
|
||||
#if DEBUG
|
||||
return await Task.FromResult(false);
|
||||
|
||||
#else
|
||||
try
|
||||
{
|
||||
using (var RequestClient = new System.Net.Http.HttpClient())
|
||||
{
|
||||
RequestClient.DefaultRequestHeaders.Add("X-Key", apiKey);
|
||||
string response = await RequestClient.GetStringAsync($"http://v2.api.iphub.info/ip/{ip}");
|
||||
var responseJson = JsonConvert.DeserializeObject<JObject>(response);
|
||||
int blockType = Convert.ToInt32(responseJson["block"]);
|
||||
return blockType == 1;
|
||||
}
|
||||
}
|
||||
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
@ -1,12 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
https://go.microsoft.com/fwlink/?LinkID=208121.
|
||||
-->
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<PublishProtocol>FileSystem</PublishProtocol>
|
||||
<Configuration>Release</Configuration>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<PublishDir>C:\Projects\IW4M-Admin\Publish\Windows</PublishDir>
|
||||
</PropertyGroup>
|
||||
</Project>
|
180
Application/RconParsers/BaseRConParser.cs
Normal file
180
Application/RconParsers/BaseRConParser.cs
Normal file
@ -0,0 +1,180 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Exceptions;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.RCon;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using static SharedLibraryCore.Server;
|
||||
|
||||
namespace IW4MAdmin.Application.RconParsers
|
||||
{
|
||||
class BaseRConParser : IRConParser
|
||||
{
|
||||
public BaseRConParser()
|
||||
{
|
||||
Configuration = new DynamicRConParserConfiguration()
|
||||
{
|
||||
CommandPrefixes = new CommandPrefix()
|
||||
{
|
||||
Tell = "tell {0} {1}",
|
||||
Say = "say {0}",
|
||||
Kick = "clientkick {0} \"{1}\"",
|
||||
Ban = "clientkick {0} \"{1}\"",
|
||||
TempBan = "tempbanclient {0} \"{1}\"",
|
||||
RConCommand = "ÿÿÿÿrcon {0} {1}",
|
||||
RConGetDvar = "ÿÿÿÿrcon {0} {1}",
|
||||
RConSetDvar = "ÿÿÿÿrcon {0} set {1}",
|
||||
RConGetStatus = "ÿÿÿÿgetstatus",
|
||||
RConGetInfo = "ÿÿÿÿgetinfo",
|
||||
RConResponse = "ÿÿÿÿprint",
|
||||
},
|
||||
};
|
||||
|
||||
Configuration.Status.Pattern = @"^ *([0-9]+) +-?([0-9]+) +((?:[A-Z]+|[0-9]+)) +((?:[a-z]|[0-9]){8,32}|(?:[a-z]|[0-9]){8,32}|bot[0-9]+|(?:[0-9]+)) +(.{0,32}) +([0-9]+) +(\d+\.\d+\.\d+.\d+\:-*\d{1,5}|0+.0+:-*\d{1,5}|loopback) +(-*[0-9]+) +([0-9]+) *$";
|
||||
Configuration.Status.AddMapping(ParserRegex.GroupType.RConClientNumber, 1);
|
||||
Configuration.Status.AddMapping(ParserRegex.GroupType.RConScore, 2);
|
||||
Configuration.Status.AddMapping(ParserRegex.GroupType.RConPing, 3);
|
||||
Configuration.Status.AddMapping(ParserRegex.GroupType.RConNetworkId, 4);
|
||||
Configuration.Status.AddMapping(ParserRegex.GroupType.RConName, 5);
|
||||
Configuration.Status.AddMapping(ParserRegex.GroupType.RConIpAddress, 7);
|
||||
|
||||
Configuration.Dvar.Pattern = "^\"(.+)\" is: \"(.+)?\" default: \"(.+)?\"\n(?:latched: \"(.+)?\"\n)? *(.+)$";
|
||||
Configuration.Dvar.AddMapping(ParserRegex.GroupType.RConDvarName, 1);
|
||||
Configuration.Dvar.AddMapping(ParserRegex.GroupType.RConDvarValue, 2);
|
||||
Configuration.Dvar.AddMapping(ParserRegex.GroupType.RConDvarDefaultValue, 3);
|
||||
Configuration.Dvar.AddMapping(ParserRegex.GroupType.RConDvarLatchedValue, 4);
|
||||
Configuration.Dvar.AddMapping(ParserRegex.GroupType.RConDvarDomain, 5);
|
||||
}
|
||||
|
||||
public IRConParserConfiguration Configuration { get; set; }
|
||||
|
||||
public string Version { get; set; } = "CoD";
|
||||
public Game GameName { get; set; } = Game.COD;
|
||||
public bool CanGenerateLogPath { get; set; } = true;
|
||||
|
||||
public async Task<string[]> ExecuteCommandAsync(Connection connection, string command)
|
||||
{
|
||||
var response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, command);
|
||||
return response.Skip(1).ToArray();
|
||||
}
|
||||
|
||||
public async Task<Dvar<T>> GetDvarAsync<T>(Connection connection, string dvarName)
|
||||
{
|
||||
string[] lineSplit = await connection.SendQueryAsync(StaticHelpers.QueryType.GET_DVAR, dvarName);
|
||||
string response = string.Join('\n', lineSplit.Skip(1));
|
||||
|
||||
if (!lineSplit[0].Contains(Configuration.CommandPrefixes.RConResponse))
|
||||
{
|
||||
throw new DvarException($"Could not retrieve DVAR \"{dvarName}\"");
|
||||
}
|
||||
|
||||
if (response.Contains("Unknown command"))
|
||||
{
|
||||
throw new DvarException($"DVAR \"{dvarName}\" does not exist");
|
||||
}
|
||||
|
||||
var match = Regex.Match(response, Configuration.Dvar.Pattern);
|
||||
|
||||
if (!match.Success)
|
||||
{
|
||||
throw new DvarException($"Could not retrieve DVAR \"{dvarName}\"");
|
||||
}
|
||||
|
||||
string value = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarValue]].Value.StripColors();
|
||||
string defaultValue = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarDefaultValue]].Value.StripColors();
|
||||
string latchedValue = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarLatchedValue]].Value.StripColors();
|
||||
|
||||
return new Dvar<T>()
|
||||
{
|
||||
Name = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarName]].Value.StripColors(),
|
||||
Value = string.IsNullOrEmpty(value) ? default(T) : (T)Convert.ChangeType(value, typeof(T)),
|
||||
DefaultValue = string.IsNullOrEmpty(defaultValue) ? default(T) : (T)Convert.ChangeType(defaultValue, typeof(T)),
|
||||
LatchedValue = string.IsNullOrEmpty(latchedValue) ? default(T) : (T)Convert.ChangeType(latchedValue, typeof(T)),
|
||||
Domain = match.Groups[Configuration.Dvar.GroupMapping[ParserRegex.GroupType.RConDvarDomain]].Value.StripColors()
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<List<EFClient>> GetStatusAsync(Connection connection)
|
||||
{
|
||||
string[] response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND_STATUS);
|
||||
return ClientsFromStatus(response);
|
||||
}
|
||||
|
||||
public async Task<bool> SetDvarAsync(Connection connection, string dvarName, object dvarValue)
|
||||
{
|
||||
return (await connection.SendQueryAsync(StaticHelpers.QueryType.SET_DVAR, $"{dvarName} {dvarValue}")).Length > 0;
|
||||
}
|
||||
|
||||
private List<EFClient> ClientsFromStatus(string[] Status)
|
||||
{
|
||||
List<EFClient> StatusPlayers = new List<EFClient>();
|
||||
|
||||
if (Status.Length < 4)
|
||||
{
|
||||
throw new ServerException("Unexpected status response received");
|
||||
}
|
||||
|
||||
int validMatches = 0;
|
||||
foreach (string statusLine in Status)
|
||||
{
|
||||
string responseLine = statusLine.Trim();
|
||||
|
||||
var regex = Regex.Match(responseLine, Configuration.Status.Pattern, RegexOptions.IgnoreCase);
|
||||
|
||||
if (regex.Success)
|
||||
{
|
||||
validMatches++;
|
||||
int clientNumber = int.Parse(regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConClientNumber]].Value);
|
||||
int score = int.Parse(regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConScore]].Value);
|
||||
|
||||
int ping = 999;
|
||||
|
||||
// their state can be CNCT, ZMBI etc
|
||||
if (regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConPing]].Value.Length <= 3)
|
||||
{
|
||||
ping = int.Parse(regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConPing]].Value);
|
||||
}
|
||||
|
||||
long networkId = regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConNetworkId]].Value.ConvertLong();
|
||||
string name = regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConName]].Value.StripColors().Trim();
|
||||
int? ip = regex.Groups[Configuration.Status.GroupMapping[ParserRegex.GroupType.RConIpAddress]].Value.Split(':')[0].ConvertToIP();
|
||||
|
||||
var client = new EFClient()
|
||||
{
|
||||
CurrentAlias = new EFAlias()
|
||||
{
|
||||
Name = name
|
||||
},
|
||||
NetworkId = networkId,
|
||||
ClientNumber = clientNumber,
|
||||
IPAddress = ip,
|
||||
Ping = ping,
|
||||
Score = score,
|
||||
IsBot = ip == null,
|
||||
State = EFClient.ClientState.Connecting
|
||||
};
|
||||
|
||||
//// they've not fully connected yet
|
||||
//if (!client.IsBot && ping == 999)
|
||||
//{
|
||||
// continue;
|
||||
//}
|
||||
|
||||
StatusPlayers.Add(client);
|
||||
}
|
||||
}
|
||||
|
||||
// this happens if status is requested while map is rotating
|
||||
if (Status.Length > 5 && validMatches == 0)
|
||||
{
|
||||
throw new ServerException("Server is rotating map");
|
||||
}
|
||||
|
||||
return StatusPlayers;
|
||||
}
|
||||
}
|
||||
}
|
10
Application/RconParsers/DynamicRConParser.cs
Normal file
10
Application/RconParsers/DynamicRConParser.cs
Normal file
@ -0,0 +1,10 @@
|
||||
namespace IW4MAdmin.Application.RconParsers
|
||||
{
|
||||
/// <summary>
|
||||
/// empty implementation of the IW4RConParser
|
||||
/// allows script plugins to generate dynamic RCon parsers
|
||||
/// </summary>
|
||||
sealed internal class DynamicRConParser : BaseRConParser
|
||||
{
|
||||
}
|
||||
}
|
18
Application/RconParsers/DynamicRConParserConfiguration.cs
Normal file
18
Application/RconParsers/DynamicRConParserConfiguration.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.RCon;
|
||||
|
||||
namespace IW4MAdmin.Application.RconParsers
|
||||
{
|
||||
/// <summary>
|
||||
/// generic implementation of the IRConParserConfiguration
|
||||
/// allows script plugins to generate dynamic RCon configurations
|
||||
/// </summary>
|
||||
sealed internal class DynamicRConParserConfiguration : IRConParserConfiguration
|
||||
{
|
||||
public CommandPrefix CommandPrefixes { get; set; }
|
||||
public ParserRegex Status { get; set; } = new ParserRegex();
|
||||
public ParserRegex Dvar { get; set; } = new ParserRegex();
|
||||
public bool WaitForResponse { get; set; } = true;
|
||||
}
|
||||
}
|
@ -1,115 +0,0 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.RCon;
|
||||
using SharedLibraryCore.Exceptions;
|
||||
|
||||
namespace Application.RconParsers
|
||||
{
|
||||
class IW4RConParser : IRConParser
|
||||
{
|
||||
private static CommandPrefix Prefixes = new CommandPrefix()
|
||||
{
|
||||
Tell = "tellraw {0} {1}",
|
||||
Say = "sayraw {0}",
|
||||
Kick = "clientkick {0} \"{1}\"",
|
||||
Ban = "clientkick {0} \"{1}\"",
|
||||
TempBan = "tempbanclient {0} \"{1}\""
|
||||
};
|
||||
|
||||
public async Task<string[]> ExecuteCommandAsync(Connection connection, string command)
|
||||
{
|
||||
return (await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, command)).Skip(1).ToArray();
|
||||
}
|
||||
|
||||
public async Task<Dvar<T>> GetDvarAsync<T>(Connection connection, string dvarName)
|
||||
{
|
||||
string[] LineSplit = await connection.SendQueryAsync(StaticHelpers.QueryType.DVAR, dvarName);
|
||||
|
||||
if (LineSplit.Length < 3)
|
||||
{
|
||||
var e = new DvarException($"DVAR \"{dvarName}\" does not exist");
|
||||
e.Data["dvar_name"] = dvarName;
|
||||
throw e;
|
||||
}
|
||||
|
||||
string[] ValueSplit = LineSplit[1].Split(new char[] { '"' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
|
||||
if (ValueSplit.Length < 5)
|
||||
{
|
||||
var e = new DvarException($"DVAR \"{dvarName}\" does not exist");
|
||||
e.Data["dvar_name"] = dvarName;
|
||||
throw e;
|
||||
}
|
||||
|
||||
string DvarName = Regex.Replace(ValueSplit[0], @"\^[0-9]", "");
|
||||
string DvarCurrentValue = Regex.Replace(ValueSplit[2], @"\^[0-9]", "");
|
||||
string DvarDefaultValue = Regex.Replace(ValueSplit[4], @"\^[0-9]", "");
|
||||
|
||||
return new Dvar<T>(DvarName)
|
||||
{
|
||||
Value = (T)Convert.ChangeType(DvarCurrentValue, typeof(T))
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<List<Player>> GetStatusAsync(Connection connection)
|
||||
{
|
||||
string[] response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, "status");
|
||||
return ClientsFromStatus(response);
|
||||
}
|
||||
|
||||
public async Task<bool> SetDvarAsync(Connection connection, string dvarName, object dvarValue)
|
||||
{
|
||||
return (await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, $"set {dvarName} {dvarValue}")).Length > 0;
|
||||
}
|
||||
|
||||
public CommandPrefix GetCommandPrefixes() => Prefixes;
|
||||
|
||||
private List<Player> ClientsFromStatus(string[] Status)
|
||||
{
|
||||
List<Player> StatusPlayers = new List<Player>();
|
||||
|
||||
if (Status.Length < 4)
|
||||
throw new ServerException("Unexpected status response received");
|
||||
|
||||
foreach (String S in Status)
|
||||
{
|
||||
String responseLine = S.Trim();
|
||||
|
||||
if (Regex.Matches(responseLine, @" *^\d+", RegexOptions.IgnoreCase).Count > 0)
|
||||
{
|
||||
String[] playerInfo = responseLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
int cID = -1;
|
||||
int Ping = -1;
|
||||
Int32.TryParse(playerInfo[2], out Ping);
|
||||
String cName = Encoding.UTF8.GetString(Encoding.Convert(Utilities.EncodingType, Encoding.UTF8, Utilities.EncodingType.GetBytes(responseLine.Substring(46, 18).StripColors().Trim())));
|
||||
long npID = Regex.Match(responseLine, @"([a-z]|[0-9]){16}", RegexOptions.IgnoreCase).Value.ConvertLong();
|
||||
int.TryParse(playerInfo[0], out cID);
|
||||
var regex = Regex.Match(responseLine, @"\d+\.\d+\.\d+.\d+\:\d{1,5}");
|
||||
int cIP = regex.Value.Split(':')[0].ConvertToIP();
|
||||
regex = Regex.Match(responseLine, @"[0-9]{1,2}\s+[0-9]+\s+");
|
||||
int score = Int32.Parse(regex.Value.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[1]);
|
||||
Player P = new Player()
|
||||
{
|
||||
Name = cName,
|
||||
NetworkId = npID,
|
||||
ClientNumber = cID,
|
||||
IPAddress = cIP,
|
||||
Ping = Ping,
|
||||
Score = score,
|
||||
IsBot = npID == -1
|
||||
};
|
||||
StatusPlayers.Add(P);
|
||||
}
|
||||
}
|
||||
|
||||
return StatusPlayers;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,198 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
using SharedLibraryCore.RCon;
|
||||
using SharedLibraryCore.Exceptions;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
|
||||
namespace Application.RconParsers
|
||||
{
|
||||
public class T6MRConParser : IRConParser
|
||||
{
|
||||
class T6MResponse
|
||||
{
|
||||
public class SInfo
|
||||
{
|
||||
public short Com_maxclients { get; set; }
|
||||
public string Game { get; set; }
|
||||
public string Gametype { get; set; }
|
||||
public string Mapname { get; set; }
|
||||
public short NumBots { get; set; }
|
||||
public short NumClients { get; set; }
|
||||
public short Round { get; set; }
|
||||
public string Sv_hostname { get; set; }
|
||||
}
|
||||
|
||||
public class PInfo
|
||||
{
|
||||
public short Assists { get; set; }
|
||||
public string Clan { get; set; }
|
||||
public short Deaths { get; set; }
|
||||
public short Downs { get; set; }
|
||||
public short Headshots { get; set; }
|
||||
public short Id { get; set; }
|
||||
public bool IsBot { get; set; }
|
||||
public short Kills { get; set; }
|
||||
public string Name { get; set; }
|
||||
public short Ping { get; set; }
|
||||
public short Revives { get; set; }
|
||||
public int Score { get; set; }
|
||||
public long Xuid { get; set; }
|
||||
public string Ip { get; set; }
|
||||
}
|
||||
|
||||
public SInfo Info { get; set; }
|
||||
public PInfo[] Players { get; set; }
|
||||
}
|
||||
|
||||
private static CommandPrefix Prefixes = new CommandPrefix()
|
||||
{
|
||||
Tell = "tell {0} {1}",
|
||||
Say = "say {0}",
|
||||
Kick = "clientKick {0}",
|
||||
Ban = "clientKick {0}",
|
||||
TempBan = "clientKick {0}"
|
||||
};
|
||||
|
||||
public CommandPrefix GetCommandPrefixes() => Prefixes;
|
||||
|
||||
public async Task<string[]> ExecuteCommandAsync(Connection connection, string command)
|
||||
{
|
||||
await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, command, false);
|
||||
return new string[] { "Command Executed" };
|
||||
}
|
||||
|
||||
public async Task<Dvar<T>> GetDvarAsync<T>(Connection connection, string dvarName)
|
||||
{
|
||||
string[] LineSplit = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, $"get {dvarName}");
|
||||
|
||||
|
||||
if (LineSplit.Length < 2)
|
||||
{
|
||||
var e = new DvarException($"DVAR \"{dvarName}\" does not exist");
|
||||
e.Data["dvar_name"] = dvarName;
|
||||
throw e;
|
||||
}
|
||||
|
||||
string[] ValueSplit = LineSplit[1].Split(new char[] { '"' });
|
||||
|
||||
if (ValueSplit.Length == 0)
|
||||
{
|
||||
var e = new DvarException($"DVAR \"{dvarName}\" does not exist");
|
||||
e.Data["dvar_name"] = dvarName;
|
||||
throw e;
|
||||
}
|
||||
|
||||
string DvarName = dvarName;
|
||||
string DvarCurrentValue = Regex.Replace(ValueSplit[1], @"\^[0-9]", "");
|
||||
|
||||
return new Dvar<T>(DvarName)
|
||||
{
|
||||
Value = (T)Convert.ChangeType(DvarCurrentValue, typeof(T))
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<List<Player>> GetStatusAsync(Connection connection)
|
||||
{
|
||||
string[] response = await connection.SendQueryAsync(StaticHelpers.QueryType.COMMAND, "status");
|
||||
return ClientsFromStatus(response);
|
||||
|
||||
//return ClientsFromResponse(connection);
|
||||
}
|
||||
|
||||
public async Task<bool> SetDvarAsync(Connection connection, string dvarName, object dvarValue)
|
||||
{
|
||||
// T6M doesn't respond with anything when a value is set, so we can only hope for the best :c
|
||||
await connection.SendQueryAsync(StaticHelpers.QueryType.DVAR, $"set {dvarName} {dvarValue}", false);
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<List<Player>> ClientsFromResponse(Connection conn)
|
||||
{
|
||||
using (var client = new HttpClient())
|
||||
{
|
||||
client.BaseAddress = new Uri($"http://{conn.Endpoint.Address}:{conn.Endpoint.Port}/");
|
||||
|
||||
try
|
||||
{
|
||||
var parameters = new FormUrlEncodedContent(new[]
|
||||
{
|
||||
new KeyValuePair<string, string>("rcon_password", conn.RConPassword)
|
||||
});
|
||||
|
||||
var serverResponse = await client.PostAsync("/info", parameters);
|
||||
var serverResponseObject = Newtonsoft.Json.JsonConvert.DeserializeObject<T6MResponse>(await serverResponse.Content.ReadAsStringAsync());
|
||||
|
||||
return serverResponseObject.Players.Select(p => new Player()
|
||||
{
|
||||
Name = p.Name,
|
||||
NetworkId = p.Xuid,
|
||||
ClientNumber = p.Id,
|
||||
IPAddress = p.Ip.Split(':')[0].ConvertToIP(),
|
||||
Ping = p.Ping,
|
||||
Score = p.Score,
|
||||
IsBot = p.IsBot,
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
catch (HttpRequestException e)
|
||||
{
|
||||
throw new NetworkException(e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private List<Player> ClientsFromStatus(string[] status)
|
||||
{
|
||||
List<Player> StatusPlayers = new List<Player>();
|
||||
|
||||
foreach (string statusLine in status)
|
||||
{
|
||||
String responseLine = statusLine;
|
||||
|
||||
if (Regex.Matches(responseLine, @"^ *\d+", RegexOptions.IgnoreCase).Count > 0) // its a client line!
|
||||
{
|
||||
String[] playerInfo = responseLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
|
||||
int clientId = -1;
|
||||
int Ping = -1;
|
||||
|
||||
Int32.TryParse(playerInfo[3], out Ping);
|
||||
var regex = Regex.Match(responseLine, @"\^7.*\ +0 ");
|
||||
string name = Encoding.UTF8.GetString(Encoding.Convert(Utilities.EncodingType, Encoding.UTF8, Utilities.EncodingType.GetBytes(regex.Value.Substring(0, regex.Value.Length - 2).StripColors().Trim())));
|
||||
long networkId = playerInfo[4].ConvertLong();
|
||||
int.TryParse(playerInfo[0], out clientId);
|
||||
regex = Regex.Match(responseLine, @"\d+\.\d+\.\d+.\d+\:\d{1,5}");
|
||||
#if DEBUG
|
||||
Ping = 1;
|
||||
#endif
|
||||
int ipAddress = regex.Value.Split(':')[0].ConvertToIP();
|
||||
regex = Regex.Match(responseLine, @"[0-9]{1,2}\s+[0-9]+\s+");
|
||||
int score = 0;
|
||||
// todo: fix this when T6M score is valid ;)
|
||||
//int score = Int32.Parse(playerInfo[1]);
|
||||
|
||||
StatusPlayers.Add(new Player()
|
||||
{
|
||||
Name = name,
|
||||
NetworkId = networkId,
|
||||
ClientNumber = clientId,
|
||||
IPAddress = ipAddress,
|
||||
Ping = Ping,
|
||||
Score = score,
|
||||
IsBot = networkId < 1
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return StatusPlayers;
|
||||
}
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
214
DiscordWebhook/DiscordWebhook.py
Normal file
214
DiscordWebhook/DiscordWebhook.py
Normal file
@ -0,0 +1,214 @@
|
||||
import requests
|
||||
import time
|
||||
import json
|
||||
import collections
|
||||
import os
|
||||
|
||||
# the following classes model the discord webhook api parameters
|
||||
class WebhookAuthor():
|
||||
def __init__(self, name=None, url=None, icon_url=None):
|
||||
if name:
|
||||
self.name = name
|
||||
if url:
|
||||
self.url = url
|
||||
if icon_url:
|
||||
self.icon_url = icon_url
|
||||
|
||||
class WebhookField():
|
||||
def __init__(self, name=None, value=None, inline=False):
|
||||
if name:
|
||||
self.name = name
|
||||
if value:
|
||||
self.value = value
|
||||
if inline:
|
||||
self.inline = inline
|
||||
|
||||
class WebhookEmbed():
|
||||
def __init__(self):
|
||||
self.author = ''
|
||||
self.title = ''
|
||||
self.url = ''
|
||||
self.description = ''
|
||||
self.color = 0
|
||||
self.fields = []
|
||||
self.thumbnail = {}
|
||||
|
||||
class WebhookParams():
|
||||
def __init__(self, username=None, avatar_url=None, content=None):
|
||||
self.username = ''
|
||||
self.avatar_url = ''
|
||||
self.content = ''
|
||||
self.embeds = []
|
||||
|
||||
# quick way to convert all the objects to a nice json object
|
||||
def to_json(self):
|
||||
return json.dumps(self, default=lambda o: o.__dict__, sort_keys=True)
|
||||
|
||||
# gets the relative link to a user's profile
|
||||
def get_client_profile(profile_id):
|
||||
return u'{}/Client/ProfileAsync/{}'.format(base_url, profile_id)
|
||||
|
||||
def get_client_profile_markdown(client_name, profile_id):
|
||||
return u'[{}]({})'.format(client_name, get_client_profile(profile_id))
|
||||
|
||||
#todo: exception handling for opening the file
|
||||
if os.getenv("DEBUG"):
|
||||
config_file_name = 'config.dev.json'
|
||||
else:
|
||||
config_file_name = 'config.json'
|
||||
|
||||
with open(config_file_name) as json_config_file:
|
||||
json_config = json.load(json_config_file)
|
||||
|
||||
# this should be an URL to an IP or FQN to an IW4MAdmin instance
|
||||
# ie http://127.0.0.1 or http://IW4MAdmin.com
|
||||
base_url = json_config['IW4MAdminUrl']
|
||||
end_point = '/api/event'
|
||||
request_url = base_url + end_point
|
||||
# this should be the full discord webhook url
|
||||
# ie https://discordapp.com/api/webhooks/<id>/<token>
|
||||
discord_webhook_notification_url = json_config['DiscordWebhookNotificationUrl']
|
||||
discord_webhook_information_url = json_config['DiscordWebhookInformationUrl']
|
||||
# this should be the numerical id of the discord group
|
||||
# 12345678912345678
|
||||
notify_role_ids = json_config['NotifyRoleIds']
|
||||
|
||||
def get_new_events():
|
||||
events = []
|
||||
response = requests.get(request_url)
|
||||
data = response.json()
|
||||
should_notify = False
|
||||
|
||||
for event in data:
|
||||
# commonly used event info items
|
||||
event_type = event['eventType']['name']
|
||||
server_name = event['ownerEntity']['name']
|
||||
|
||||
if event['originEntity']:
|
||||
origin_client_name = event['originEntity']['name']
|
||||
origin_client_id = int(event['originEntity']['id'])
|
||||
|
||||
if event['targetEntity']:
|
||||
target_client_name = event['targetEntity']['name'] or ''
|
||||
target_client_id = int(event['targetEntity']['id']) or 0
|
||||
|
||||
webhook_item = WebhookParams()
|
||||
webhook_item_embed = WebhookEmbed()
|
||||
|
||||
#todo: the following don't need to be generated every time, as it says the same
|
||||
webhook_item.username = 'IW4MAdmin'
|
||||
webhook_item.avatar_url = 'https://raidmax.org/IW4MAdmin/img/iw4adminicon-3.png'
|
||||
webhook_item_embed.color = 31436
|
||||
webhook_item_embed.url = base_url
|
||||
webhook_item_embed.thumbnail = { 'url' : 'https://raidmax.org/IW4MAdmin/img/iw4adminicon-3.png' }
|
||||
webhook_item.embeds.append(webhook_item_embed)
|
||||
|
||||
# the server should be visible on all event types
|
||||
server_field = WebhookField('Server', server_name)
|
||||
webhook_item_embed.fields.append(server_field)
|
||||
|
||||
role_ids_string = ''
|
||||
for id in notify_role_ids:
|
||||
role_ids_string += '\r\n<@&{}>\r\n'.format(id)
|
||||
|
||||
if event_type == 'Report':
|
||||
report_reason = event['extraInfo']
|
||||
|
||||
report_reason_field = WebhookField('Reason', report_reason)
|
||||
reported_by_field = WebhookField('By', get_client_profile_markdown(origin_client_name, origin_client_id))
|
||||
reported_field = WebhookField('Reported Player',get_client_profile_markdown(target_client_name, target_client_id))
|
||||
|
||||
# add each fields to the embed
|
||||
webhook_item_embed.title = 'Player Reported'
|
||||
webhook_item_embed.fields.append(reported_field)
|
||||
webhook_item_embed.fields.append(reported_by_field)
|
||||
webhook_item_embed.fields.append(report_reason_field)
|
||||
|
||||
should_notify = True
|
||||
|
||||
elif event_type == 'Ban':
|
||||
ban_reason = event['extraInfo']
|
||||
ban_reason_field = WebhookField('Reason', ban_reason)
|
||||
banned_by_field = WebhookField('By', get_client_profile_markdown(origin_client_name, origin_client_id))
|
||||
banned_field = WebhookField('Banned Player', get_client_profile_markdown(target_client_name, target_client_id))
|
||||
|
||||
# add each fields to the embed
|
||||
webhook_item_embed.title = 'Player Banned'
|
||||
webhook_item_embed.fields.append(banned_field)
|
||||
webhook_item_embed.fields.append(banned_by_field)
|
||||
webhook_item_embed.fields.append(ban_reason_field)
|
||||
|
||||
should_notify = True
|
||||
|
||||
elif event_type == 'Connect':
|
||||
connected_field = WebhookField('Connected Player', get_client_profile_markdown(origin_client_name, origin_client_id))
|
||||
webhook_item_embed.title = 'Player Connected'
|
||||
webhook_item_embed.fields.append(connected_field)
|
||||
|
||||
elif event_type == 'Disconnect':
|
||||
disconnected_field = WebhookField('Disconnected Player', get_client_profile_markdown(origin_client_name, origin_client_id))
|
||||
webhook_item_embed.title = 'Player Disconnected'
|
||||
webhook_item_embed.fields.append(disconnected_field)
|
||||
|
||||
elif event_type == 'Say':
|
||||
say_client_field = WebhookField('Player', get_client_profile_markdown(origin_client_name, origin_client_id))
|
||||
message_field = WebhookField('Message', event['extraInfo'])
|
||||
|
||||
webhook_item_embed.title = 'Message From Player'
|
||||
webhook_item_embed.fields.append(say_client_field)
|
||||
webhook_item_embed.fields.append(message_field)
|
||||
|
||||
#if event_type == 'ScriptKill' or event_type == 'Kill':
|
||||
# kill_str = '{} killed {}'.format(get_client_profile_markdown(origin_client_name, origin_client_id),
|
||||
# get_client_profile_markdown(target_client_name, target_client_id))
|
||||
# killed_field = WebhookField('Kill Information', kill_str)
|
||||
# webhook_item_embed.title = 'Player Killed'
|
||||
# webhook_item_embed.fields.append(killed_field)
|
||||
|
||||
#todo: handle other events
|
||||
else:
|
||||
continue
|
||||
|
||||
#make sure there's at least one group to notify
|
||||
if len(notify_role_ids) > 0:
|
||||
# unfortunately only the content can be used to to notify members in groups
|
||||
#embed content shows the role but doesn't notify
|
||||
webhook_item.content = role_ids_string
|
||||
|
||||
events.append({'item' : webhook_item, 'notify' : should_notify})
|
||||
|
||||
return events
|
||||
|
||||
# sends the data to the webhook location
|
||||
def execute_webhook(data):
|
||||
for event in data:
|
||||
event_json = event['item'].to_json()
|
||||
url = None
|
||||
|
||||
if event['notify']:
|
||||
url = discord_webhook_notification_url
|
||||
else:
|
||||
if len(discord_webhook_information_url) > 0:
|
||||
url = discord_webhook_information_url
|
||||
|
||||
if url :
|
||||
response = requests.post(url,
|
||||
data=event_json,
|
||||
headers={'Content-type' : 'application/json'})
|
||||
|
||||
# grabs new events and executes the webhook fo each valid event
|
||||
def run():
|
||||
failed_count = 1
|
||||
print('starting polling for events')
|
||||
while True:
|
||||
try:
|
||||
new_events = get_new_events()
|
||||
execute_webhook(new_events)
|
||||
except Exception as e:
|
||||
print('failed to get new events ({})'.format(failed_count))
|
||||
print(e)
|
||||
failed_count += 1
|
||||
time.sleep(5)
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
99
DiscordWebhook/DiscordWebhook.pyproj
Normal file
99
DiscordWebhook/DiscordWebhook.pyproj
Normal file
@ -0,0 +1,99 @@
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>15a81d6e-7502-46ce-8530-0647a380b5f4</ProjectGuid>
|
||||
<ProjectHome>.</ProjectHome>
|
||||
<StartupFile>DiscordWebhook.py</StartupFile>
|
||||
<SearchPath>
|
||||
</SearchPath>
|
||||
<WorkingDirectory>.</WorkingDirectory>
|
||||
<OutputPath>.</OutputPath>
|
||||
<Name>DiscordWebhook</Name>
|
||||
<SuppressCollectPythonCloudServiceFiles>true</SuppressCollectPythonCloudServiceFiles>
|
||||
<RootNamespace>DiscordWebhook</RootNamespace>
|
||||
<InterpreterId>MSBuild|env|$(MSBuildProjectFullPath)</InterpreterId>
|
||||
<IsWindowsApplication>False</IsWindowsApplication>
|
||||
<LaunchProvider>Standard Python launcher</LaunchProvider>
|
||||
<EnableNativeCodeDebugging>False</EnableNativeCodeDebugging>
|
||||
<Environment>DEBUG=True</Environment>
|
||||
<PublishUrl>C:\Projects\IW4M-Admin\Publish\WindowsPrerelease\DiscordWebhook</PublishUrl>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Prerelease' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
|
||||
<OutputPath>bin\Prerelease\</OutputPath>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="DiscordWebhook.py" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Interpreter Include="env\">
|
||||
<Id>env</Id>
|
||||
<Version>3.6</Version>
|
||||
<Description>env (Python 3.6 (64-bit))</Description>
|
||||
<InterpreterPath>Scripts\python.exe</InterpreterPath>
|
||||
<WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath>
|
||||
<PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable>
|
||||
<Architecture>X64</Architecture>
|
||||
</Interpreter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="config.json">
|
||||
<Publish>True</Publish>
|
||||
</Content>
|
||||
<Content Include="requirements.txt">
|
||||
<Publish>True</Publish>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets" />
|
||||
<!-- Uncomment the CoreCompile target to enable the Build command in
|
||||
Visual Studio and specify your pre- and post-build commands in
|
||||
the BeforeBuild and AfterBuild targets below. -->
|
||||
<!--<Target Name="CoreCompile" />-->
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<AutoAssignPort>True</AutoAssignPort>
|
||||
<UseCustomServer>True</UseCustomServer>
|
||||
<CustomServerUrl>http://localhost</CustomServerUrl>
|
||||
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}" User="">
|
||||
<WebProjectProperties>
|
||||
<StartPageUrl>
|
||||
</StartPageUrl>
|
||||
<StartAction>CurrentPage</StartAction>
|
||||
<AspNetDebugging>True</AspNetDebugging>
|
||||
<SilverlightDebugging>False</SilverlightDebugging>
|
||||
<NativeDebugging>False</NativeDebugging>
|
||||
<SQLDebugging>False</SQLDebugging>
|
||||
<ExternalProgram>
|
||||
</ExternalProgram>
|
||||
<StartExternalURL>
|
||||
</StartExternalURL>
|
||||
<StartCmdLineArguments>
|
||||
</StartCmdLineArguments>
|
||||
<StartWorkingDirectory>
|
||||
</StartWorkingDirectory>
|
||||
<EnableENC>False</EnableENC>
|
||||
<AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
6
DiscordWebhook/config.json
Normal file
6
DiscordWebhook/config.json
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"IW4MAdminUrl": "",
|
||||
"DiscordWebhookNotificationUrl": "",
|
||||
"DiscordWebhookInformationUrl": "",
|
||||
"NotifyRoleIds": []
|
||||
}
|
7
DiscordWebhook/requirements.txt
Normal file
7
DiscordWebhook/requirements.txt
Normal file
@ -0,0 +1,7 @@
|
||||
certifi>=2018.4.16
|
||||
chardet>=3.0.4
|
||||
idna>=2.7
|
||||
pip>=18.0
|
||||
requests>=2.19.1
|
||||
setuptools>=39.0.1
|
||||
urllib3>=1.23
|
118
GameLogServer/GameLogServer.pyproj
Normal file
118
GameLogServer/GameLogServer.pyproj
Normal file
@ -0,0 +1,118 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0">
|
||||
<PropertyGroup>
|
||||
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>42efda12-10d3-4c40-a210-9483520116bc</ProjectGuid>
|
||||
<ProjectHome>.</ProjectHome>
|
||||
<ProjectTypeGuids>{789894c7-04a9-4a11-a6b5-3f4435165112};{1b580a1a-fdb3-4b32-83e1-6407eb2722e6};{349c5851-65df-11da-9384-00065b846f21};{888888a0-9f3d-457c-b088-3a5042f75d52}</ProjectTypeGuids>
|
||||
<StartupFile>runserver.py</StartupFile>
|
||||
<SearchPath>
|
||||
</SearchPath>
|
||||
<WorkingDirectory>.</WorkingDirectory>
|
||||
<LaunchProvider>Standard Python launcher</LaunchProvider>
|
||||
<WebBrowserUrl>http://localhost</WebBrowserUrl>
|
||||
<OutputPath>.</OutputPath>
|
||||
<SuppressCollectPythonCloudServiceFiles>true</SuppressCollectPythonCloudServiceFiles>
|
||||
<Name>GameLogServer</Name>
|
||||
<RootNamespace>GameLogServer</RootNamespace>
|
||||
<InterpreterId>MSBuild|log_env|$(MSBuildProjectFullPath)</InterpreterId>
|
||||
<EnableNativeCodeDebugging>False</EnableNativeCodeDebugging>
|
||||
<Environment>DEBUG=True</Environment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Prerelease' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
|
||||
<OutputPath>bin\Prerelease\</OutputPath>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="GameLogServer\log_reader.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="GameLogServer\restart_resource.py" />
|
||||
<Compile Include="GameLogServer\server.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="runserver.py" />
|
||||
<Compile Include="GameLogServer\__init__.py" />
|
||||
<Compile Include="GameLogServer\log_resource.py" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="GameLogServer\" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="Stable.pubxml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Interpreter Include="env\">
|
||||
<Id>env</Id>
|
||||
<Version>3.6</Version>
|
||||
<Description>env (Python 3.6 (64-bit))</Description>
|
||||
<InterpreterPath>Scripts\python.exe</InterpreterPath>
|
||||
<WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath>
|
||||
<PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable>
|
||||
<Architecture>X64</Architecture>
|
||||
</Interpreter>
|
||||
<Interpreter Include="log_env\">
|
||||
<Id>log_env</Id>
|
||||
<Version>3.6</Version>
|
||||
<Description>log_env (Python 3.6 (64-bit))</Description>
|
||||
<InterpreterPath>Scripts\python.exe</InterpreterPath>
|
||||
<WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath>
|
||||
<PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable>
|
||||
<Architecture>X64</Architecture>
|
||||
</Interpreter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="requirements.txt" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets" />
|
||||
<!-- Specify pre- and post-build commands in the BeforeBuild and
|
||||
AfterBuild targets below. -->
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<AutoAssignPort>True</AutoAssignPort>
|
||||
<UseCustomServer>True</UseCustomServer>
|
||||
<CustomServerUrl>http://localhost</CustomServerUrl>
|
||||
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}" User="">
|
||||
<WebProjectProperties>
|
||||
<StartPageUrl>
|
||||
</StartPageUrl>
|
||||
<StartAction>CurrentPage</StartAction>
|
||||
<AspNetDebugging>True</AspNetDebugging>
|
||||
<SilverlightDebugging>False</SilverlightDebugging>
|
||||
<NativeDebugging>False</NativeDebugging>
|
||||
<SQLDebugging>False</SQLDebugging>
|
||||
<ExternalProgram>
|
||||
</ExternalProgram>
|
||||
<StartExternalURL>
|
||||
</StartExternalURL>
|
||||
<StartCmdLineArguments>
|
||||
</StartCmdLineArguments>
|
||||
<StartWorkingDirectory>
|
||||
</StartWorkingDirectory>
|
||||
<EnableENC>False</EnableENC>
|
||||
<AlwaysStartWebServerOnDebug>False</AlwaysStartWebServerOnDebug>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
</Project>
|
9
GameLogServer/GameLogServer/__init__.py
Normal file
9
GameLogServer/GameLogServer/__init__.py
Normal file
@ -0,0 +1,9 @@
|
||||
"""
|
||||
The flask application package.
|
||||
"""
|
||||
|
||||
from flask import Flask
|
||||
from flask_restful import Api
|
||||
|
||||
app = Flask(__name__)
|
||||
api = Api(app)
|
85
GameLogServer/GameLogServer/log_reader.py
Normal file
85
GameLogServer/GameLogServer/log_reader.py
Normal file
@ -0,0 +1,85 @@
|
||||
import re
|
||||
import os
|
||||
import time
|
||||
|
||||
class LogReader(object):
|
||||
def __init__(self):
|
||||
self.log_file_sizes = {}
|
||||
# (if the time between checks is greater, ignore ) - in seconds
|
||||
self.max_file_time_change = 30
|
||||
|
||||
def read_file(self, path):
|
||||
# this removes old entries that are no longer valid
|
||||
try:
|
||||
self._clear_old_logs()
|
||||
except Exception as e:
|
||||
print('could not clear old logs')
|
||||
print(e)
|
||||
|
||||
if os.name != 'nt':
|
||||
path = re.sub(r'^[A-Z]\:', '', path)
|
||||
path = re.sub(r'\\+', '/', path)
|
||||
|
||||
# prevent traversing directories
|
||||
if re.search('r^.+\.\.\\.+$', path):
|
||||
return False
|
||||
# must be a valid log path and log file
|
||||
if not re.search(r'^.+[\\|\/](.+)[\\|\/].+.log$', path):
|
||||
return False
|
||||
|
||||
# get the new file size
|
||||
new_file_size = self.file_length(path)
|
||||
|
||||
# the log size was unable to be read (probably the wrong path)
|
||||
if new_file_size < 0:
|
||||
return False
|
||||
|
||||
# this is the first time the log has been requested
|
||||
if path not in self.log_file_sizes:
|
||||
self.log_file_sizes[path] = {
|
||||
'length' : new_file_size,
|
||||
'read': time.time()
|
||||
}
|
||||
return ''
|
||||
|
||||
# grab the previous values
|
||||
last_length = self.log_file_sizes[path]['length']
|
||||
file_size_difference = new_file_size - last_length
|
||||
|
||||
# update the new size and actually read the data
|
||||
self.log_file_sizes[path] = {
|
||||
'length': new_file_size,
|
||||
'read': time.time()
|
||||
}
|
||||
|
||||
new_log_info = self.get_file_lines(path, file_size_difference)
|
||||
return new_log_info
|
||||
|
||||
def get_file_lines(self, path, length):
|
||||
try:
|
||||
file_handle = open(path, 'rb')
|
||||
file_handle.seek(-length, 2)
|
||||
file_data = file_handle.read(length)
|
||||
file_handle.close()
|
||||
# using ignore errors omits the pesky 0xb2 bytes we're reading in for some reason
|
||||
return file_data.decode('utf-8', errors='ignore')
|
||||
except Exception as e:
|
||||
print('could not read the log file at {0}, wanted to read {1} bytes'.format(path, length))
|
||||
print(e)
|
||||
return False
|
||||
|
||||
def _clear_old_logs(self):
|
||||
expired_logs = [path for path in self.log_file_sizes if int(time.time() - self.log_file_sizes[path]['read']) > self.max_file_time_change]
|
||||
for log in expired_logs:
|
||||
print('removing expired log {0}'.format(log))
|
||||
del self.log_file_sizes[log]
|
||||
|
||||
def file_length(self, path):
|
||||
try:
|
||||
return os.stat(path).st_size
|
||||
except Exception as e:
|
||||
print('could not get the size of the log file at {0}'.format(path))
|
||||
print(e)
|
||||
return -1
|
||||
|
||||
reader = LogReader()
|
14
GameLogServer/GameLogServer/log_resource.py
Normal file
14
GameLogServer/GameLogServer/log_resource.py
Normal file
@ -0,0 +1,14 @@
|
||||
from flask_restful import Resource
|
||||
from GameLogServer.log_reader import reader
|
||||
from base64 import urlsafe_b64decode
|
||||
|
||||
class LogResource(Resource):
|
||||
def get(self, path):
|
||||
path = urlsafe_b64decode(path).decode('utf-8')
|
||||
log_info = reader.read_file(path)
|
||||
|
||||
return {
|
||||
'success' : log_info is not False,
|
||||
'length': 0 if log_info is False else len(log_info),
|
||||
'data': log_info
|
||||
}
|
29
GameLogServer/GameLogServer/restart_resource.py
Normal file
29
GameLogServer/GameLogServer/restart_resource.py
Normal file
@ -0,0 +1,29 @@
|
||||
#from flask_restful import Resource
|
||||
#from flask import request
|
||||
#import requests
|
||||
#import os
|
||||
#import subprocess
|
||||
#import re
|
||||
|
||||
#def get_pid_of_server_windows(port):
|
||||
# process = subprocess.Popen('netstat -aon', shell=True, stdout=subprocess.PIPE)
|
||||
# output = process.communicate()[0]
|
||||
# matches = re.search(' *(UDP) +([0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}):'+ str(port) + ' +[^\w]*([0-9]+)', output.decode('utf-8'))
|
||||
# if matches is not None:
|
||||
# return matches.group(3)
|
||||
# else:
|
||||
# return 0
|
||||
|
||||
#class RestartResource(Resource):
|
||||
# def get(self):
|
||||
# try:
|
||||
# response = requests.get('http://' + request.remote_addr + ':1624/api/restartapproved')
|
||||
# if response.status_code == 200:
|
||||
# pid = get_pid_of_server_windows(response.json()['port'])
|
||||
# subprocess.check_output("Taskkill /PID %s /F" % pid)
|
||||
# else:
|
||||
# return {}, 400
|
||||
# except Exception as e:
|
||||
# print(e)
|
||||
# return {}, 500
|
||||
# return {}, 200
|
14
GameLogServer/GameLogServer/server.py
Normal file
14
GameLogServer/GameLogServer/server.py
Normal file
@ -0,0 +1,14 @@
|
||||
from flask import Flask
|
||||
from flask_restful import Api
|
||||
from .log_resource import LogResource
|
||||
#from .restart_resource import RestartResource
|
||||
import logging
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
def init():
|
||||
log = logging.getLogger('werkzeug')
|
||||
log.setLevel(logging.ERROR)
|
||||
api = Api(app)
|
||||
api.add_resource(LogResource, '/log/<string:path>')
|
||||
#api.add_resource(RestartResource, '/restart')
|
12
GameLogServer/requirements.txt
Normal file
12
GameLogServer/requirements.txt
Normal file
@ -0,0 +1,12 @@
|
||||
aniso8601==6.0.0
|
||||
Click==7.0
|
||||
Flask==1.0.2
|
||||
Flask-RESTful==0.3.7
|
||||
itsdangerous==1.1.0
|
||||
Jinja2==2.10
|
||||
MarkupSafe==1.1.1
|
||||
pip==10.0.1
|
||||
pytz==2018.9
|
||||
setuptools==39.0.1
|
||||
six==1.12.0
|
||||
Werkzeug==0.15.2
|
15
GameLogServer/runserver.py
Normal file
15
GameLogServer/runserver.py
Normal file
@ -0,0 +1,15 @@
|
||||
"""
|
||||
This script runs the GameLogServer application using a development server.
|
||||
"""
|
||||
|
||||
from os import environ
|
||||
from GameLogServer.server import app, init
|
||||
|
||||
if __name__ == '__main__':
|
||||
HOST = environ.get('SERVER_HOST', '0.0.0.0')
|
||||
try:
|
||||
PORT = int(environ.get('SERVER_PORT', '1625'))
|
||||
except ValueError:
|
||||
PORT = 5555
|
||||
init()
|
||||
app.run('0.0.0.0', PORT, debug=False)
|
140
IW4MAdmin.sln
140
IW4MAdmin.sln
@ -1,4 +1,3 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 15
|
||||
VisualStudioVersion = 15.0.26730.16
|
||||
@ -7,8 +6,11 @@ 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
|
||||
_commands.gsc = _commands.gsc
|
||||
_customcallbacks.gsc = _customcallbacks.gsc
|
||||
README.md = README.md
|
||||
RunPublishPre.cmd = RunPublishPre.cmd
|
||||
RunPublishRelease.cmd = RunPublishRelease.cmd
|
||||
version.txt = version.txt
|
||||
EndProjectSection
|
||||
EndProject
|
||||
@ -28,7 +30,30 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Login", "Plugins\Login\Logi
|
||||
EndProject
|
||||
Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "Master", "Master\Master.pyproj", "{F5051A32-6BD0-4128-ABBA-C202EE15FC5C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Plugins\Tests\Tests.csproj", "{B72DEBFB-9D48-4076-8FF5-1FD72A830845}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tests", "Plugins\Tests\Tests.csproj", "{B72DEBFB-9D48-4076-8FF5-1FD72A830845}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IW4ScriptCommands", "Plugins\IW4ScriptCommands\IW4ScriptCommands.csproj", "{6C706CE5-A206-4E46-8712-F8C48D526091}"
|
||||
EndProject
|
||||
Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "DiscordWebhook", "DiscordWebhook\DiscordWebhook.pyproj", "{15A81D6E-7502-46CE-8530-0647A380B5F4}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ScriptPlugins", "ScriptPlugins", "{3F9ACC27-26DB-49FA-BCD2-50C54A49C9FA}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Plugins\ScriptPlugins\ParserCoD4x.js = Plugins\ScriptPlugins\ParserCoD4x.js
|
||||
Plugins\ScriptPlugins\ParserIW4x.js = Plugins\ScriptPlugins\ParserIW4x.js
|
||||
Plugins\ScriptPlugins\ParserPT6.js = Plugins\ScriptPlugins\ParserPT6.js
|
||||
Plugins\ScriptPlugins\ParserRektT5M.js = Plugins\ScriptPlugins\ParserRektT5M.js
|
||||
Plugins\ScriptPlugins\ParserTeknoMW3.js = Plugins\ScriptPlugins\ParserTeknoMW3.js
|
||||
Plugins\ScriptPlugins\SharedGUIDKick.js = Plugins\ScriptPlugins\SharedGUIDKick.js
|
||||
Plugins\ScriptPlugins\VPNDetection.js = Plugins\ScriptPlugins\VPNDetection.js
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{888888A0-9F3D-457C-B088-3A5042F75D52}") = "GameLogServer", "GameLogServer\GameLogServer.pyproj", "{42EFDA12-10D3-4C40-A210-9483520116BC}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Web", "Web", "{A848FCF1-8527-4AA8-A1AA-50D29695C678}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StatsWeb", "Plugins\Web\StatsWeb\StatsWeb.csproj", "{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutomessageFeed", "Plugins\AutomessageFeed\AutomessageFeed.csproj", "{F5815359-CFC7-44B4-9A3B-C04BACAD5836}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@ -260,6 +285,112 @@ Global
|
||||
{B72DEBFB-9D48-4076-8FF5-1FD72A830845}.Release|x64.Build.0 = Release|Any CPU
|
||||
{B72DEBFB-9D48-4076-8FF5-1FD72A830845}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{B72DEBFB-9D48-4076-8FF5-1FD72A830845}.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
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Prerelease|Any CPU.ActiveCfg = Prerelease|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Prerelease|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Prerelease|x64.ActiveCfg = Release|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Prerelease|x86.ActiveCfg = Release|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{15A81D6E-7502-46CE-8530-0647A380B5F4}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|Any CPU.ActiveCfg = Prerelease|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|x64.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|x64.Build.0 = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|x86.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Prerelease|x86.Build.0 = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|x64.Build.0 = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{42EFDA12-10D3-4C40-A210-9483520116BC}.Release|x86.Build.0 = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|Any CPU.ActiveCfg = Prerelease|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|Any CPU.Build.0 = Prerelease|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|x64.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|x64.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|x86.ActiveCfg = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Prerelease|x86.Build.0 = Debug|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|x64.Build.0 = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B}.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
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|Mixed Platforms.ActiveCfg = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|Mixed Platforms.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|x64.ActiveCfg = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|x64.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|x86.ActiveCfg = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Prerelease|x86.Build.0 = Debug|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|Mixed Platforms.Build.0 = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|x64.Build.0 = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
@ -270,6 +401,11 @@ Global
|
||||
{958FF7EC-0226-4E85-A85B-B84EC768197D} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||
{D9F2ED28-6FA5-40CA-9912-E7A849147AB1} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||
{B72DEBFB-9D48-4076-8FF5-1FD72A830845} = {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}
|
||||
{A848FCF1-8527-4AA8-A1AA-50D29695C678} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||
{776B348B-F818-4A0F-A625-D0AF8BAD3E9B} = {A848FCF1-8527-4AA8-A1AA-50D29695C678}
|
||||
{F5815359-CFC7-44B4-9A3B-C04BACAD5836} = {26E8B310-269E-46D4-A612-24601F16065F}
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {84F8F8E0-1F73-41E0-BD8D-BB6676E2EE87}
|
||||
|
@ -7,17 +7,25 @@
|
||||
<ProjectGuid>f5051a32-6bd0-4128-abba-c202ee15fc5c</ProjectGuid>
|
||||
<ProjectHome>.</ProjectHome>
|
||||
<ProjectTypeGuids>{789894c7-04a9-4a11-a6b5-3f4435165112};{1b580a1a-fdb3-4b32-83e1-6407eb2722e6};{349c5851-65df-11da-9384-00065b846f21};{888888a0-9f3d-457c-b088-3a5042f75d52}</ProjectTypeGuids>
|
||||
<StartupFile>runserver.py</StartupFile>
|
||||
<StartupFile>master\runserver.py</StartupFile>
|
||||
<SearchPath>
|
||||
</SearchPath>
|
||||
<WorkingDirectory>.</WorkingDirectory>
|
||||
<LaunchProvider>Web launcher</LaunchProvider>
|
||||
<LaunchProvider>Standard Python launcher</LaunchProvider>
|
||||
<WebBrowserUrl>http://localhost</WebBrowserUrl>
|
||||
<OutputPath>.</OutputPath>
|
||||
<SuppressCollectPythonCloudServiceFiles>true</SuppressCollectPythonCloudServiceFiles>
|
||||
<Name>Master</Name>
|
||||
<RootNamespace>Master</RootNamespace>
|
||||
<InterpreterId>MSBuild|dev_env|$(MSBuildProjectFullPath)</InterpreterId>
|
||||
<InterpreterId>MSBuild|env_master|$(MSBuildProjectFullPath)</InterpreterId>
|
||||
<IsWindowsApplication>False</IsWindowsApplication>
|
||||
<PythonRunWebServerCommand>
|
||||
</PythonRunWebServerCommand>
|
||||
<PythonDebugWebServerCommand>
|
||||
</PythonDebugWebServerCommand>
|
||||
<PythonRunWebServerCommandType>script</PythonRunWebServerCommandType>
|
||||
<PythonDebugWebServerCommandType>script</PythonDebugWebServerCommandType>
|
||||
<EnableNativeCodeDebugging>False</EnableNativeCodeDebugging>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
@ -51,27 +59,36 @@
|
||||
<Compile Include="master\models\__init__.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Master\resources\authenticate.py">
|
||||
<Compile Include="master\resources\authenticate.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="master\resources\history_graph.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Master\resources\instance.py">
|
||||
<Compile Include="master\resources\instance.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Master\resources\null.py">
|
||||
<Compile Include="master\resources\localization.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Master\resources\version.py">
|
||||
<Compile Include="master\resources\null.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Master\resources\__init__.py">
|
||||
<Compile Include="Master\resources\server.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="master\resources\version.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="master\resources\__init__.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="master\routes.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="master\runserver.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="master\schema\instanceschema.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
@ -81,33 +98,32 @@
|
||||
<Compile Include="master\schema\__init__.py">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="runserver.py" />
|
||||
<Compile Include="master\__init__.py" />
|
||||
<Compile Include="master\views.py" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Folder Include="C:\Projects\IW4M-Admin\Master\master\" />
|
||||
<Folder Include="master\" />
|
||||
<Folder Include="master\context\" />
|
||||
<Folder Include="master\models\" />
|
||||
<Folder Include="master\config\" />
|
||||
<Folder Include="master\schema\" />
|
||||
<Folder Include="Master\resources\" />
|
||||
<Folder Include="Master\static\" />
|
||||
<Folder Include="Master\templates\" />
|
||||
<Folder Include="master\static\" />
|
||||
<Folder Include="master\templates\" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="FolderProfile.pubxml" />
|
||||
<Content Include="master\config\master.json" />
|
||||
<Content Include="master\templates\serverlist.html" />
|
||||
<None Include="Release.pubxml" />
|
||||
<Content Include="requirements.txt" />
|
||||
<Content Include="Master\templates\index.html" />
|
||||
<Content Include="Master\templates\layout.html" />
|
||||
<Content Include="master\templates\index.html" />
|
||||
<Content Include="master\templates\layout.html" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Interpreter Include="dev_env\">
|
||||
<Id>dev_env</Id>
|
||||
<Interpreter Include="env_master\">
|
||||
<Id>env_master</Id>
|
||||
<Version>3.6</Version>
|
||||
<Description>dev_env (Python 3.6 (64-bit))</Description>
|
||||
<Description>env_master (Python 3.6 (64-bit))</Description>
|
||||
<InterpreterPath>Scripts\python.exe</InterpreterPath>
|
||||
<WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath>
|
||||
<PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable>
|
||||
|
@ -6,7 +6,6 @@ from flask import Flask
|
||||
from flask_restful import Resource, Api
|
||||
from flask_jwt_extended import JWTManager
|
||||
from master.context.base import Base
|
||||
import json
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config['JWT_SECRET_KEY'] = 'my key!'
|
||||
@ -14,7 +13,7 @@ app.config['PROPAGATE_EXCEPTIONS'] = True
|
||||
jwt = JWTManager(app)
|
||||
api = Api(app)
|
||||
ctx = Base()
|
||||
config = json.load(open('./master/config/master.json'))
|
||||
#config = json.load(open('./master/config/master.json'))
|
||||
|
||||
import master.routes
|
||||
import master.views
|
||||
|
@ -1,4 +1,4 @@
|
||||
{
|
||||
"current-version-stable": 2.0,
|
||||
"current-version-prerelease": 2.0
|
||||
"current-version-stable": 2.1,
|
||||
"current-version-prerelease": 2.1
|
||||
}
|
@ -15,9 +15,9 @@ class Base():
|
||||
self.scheduler.start()
|
||||
self.scheduler.add_job(
|
||||
func=self._remove_staleinstances,
|
||||
trigger=IntervalTrigger(seconds=120),
|
||||
trigger=IntervalTrigger(seconds=60),
|
||||
id='stale_instance_remover',
|
||||
name='Remove stale instances if no heartbeat in 120 seconds',
|
||||
name='Remove stale instances if no heartbeat in 60 seconds',
|
||||
replace_existing=True
|
||||
)
|
||||
self.scheduler.add_job(
|
||||
@ -37,10 +37,11 @@ class Base():
|
||||
client_num += server.clientnum
|
||||
self.history.add_client_history(client_num)
|
||||
self.history.add_instance_history(len(self.instance_list))
|
||||
self.history.add_server_history(len(servers))
|
||||
|
||||
def _remove_staleinstances(self):
|
||||
for key, value in list(self.instance_list.items()):
|
||||
if int(time.time()) - value.last_heartbeat > 120:
|
||||
if int(time.time()) - value.last_heartbeat > 60:
|
||||
print('[_remove_staleinstances] removing stale instance {id}'.format(id=key))
|
||||
del self.instance_list[key]
|
||||
del self.token_list[key]
|
||||
|
@ -5,17 +5,26 @@ class History():
|
||||
def __init__(self):
|
||||
self.client_history = list()
|
||||
self.instance_history = list()
|
||||
self.server_history = list()
|
||||
|
||||
def add_client_history(self, client_num):
|
||||
if len(self.client_history) > 1440:
|
||||
if len(self.client_history) > 2880:
|
||||
self.client_history = self.client_history[1:]
|
||||
self.client_history.append({
|
||||
'count' : client_num,
|
||||
'time' : int(time.time())
|
||||
})
|
||||
|
||||
def add_server_history(self, server_num):
|
||||
if len(self.server_history) > 2880:
|
||||
self.server_history = self.server_history[1:]
|
||||
self.server_history.append({
|
||||
'count' : server_num,
|
||||
'time' : int(time.time())
|
||||
})
|
||||
|
||||
def add_instance_history(self, instance_num):
|
||||
if len(self.instance_history) > 1440:
|
||||
if len(self.instance_history) > 2880:
|
||||
self.instance_history = self.instance_history[1:]
|
||||
self.instance_history.append({
|
||||
'count' : instance_num,
|
||||
|
@ -1,14 +1,16 @@
|
||||
|
||||
class ServerModel(object):
|
||||
def __init__(self, id, port, game, hostname, clientnum, maxclientnum, map, gametype):
|
||||
def __init__(self, id, port, game, hostname, clientnum, maxclientnum, map, gametype, ip, version):
|
||||
self.id = id
|
||||
self.port = port
|
||||
self.version = version
|
||||
self.game = game
|
||||
self.hostname = hostname
|
||||
self.clientnum = clientnum
|
||||
self.maxclientnum = maxclientnum
|
||||
self.map = map
|
||||
self.gametype = gametype
|
||||
self.ip = ip
|
||||
|
||||
def __repr__(self):
|
||||
return '<ServerModel(id={id})>'.format(id=self.id)
|
||||
|
@ -8,10 +8,11 @@ import datetime
|
||||
class Authenticate(Resource):
|
||||
def post(self):
|
||||
instance_id = request.json['id']
|
||||
if ctx.get_token(instance_id) is not False:
|
||||
return { 'message' : 'that id already has a token'}, 401
|
||||
else:
|
||||
expires = datetime.timedelta(days=1)
|
||||
token = create_access_token(instance_id, expires_delta=expires)
|
||||
ctx.add_token(instance_id, token)
|
||||
return { 'access_token' : token }, 200
|
||||
#todo: see why this is failing
|
||||
#if ctx.get_token(instance_id) is not False:
|
||||
# return { 'message' : 'that id already has a token'}, 401
|
||||
#else:
|
||||
expires = datetime.timedelta(days=30)
|
||||
token = create_access_token(instance_id, expires_delta=expires)
|
||||
ctx.add_token(instance_id, token)
|
||||
return { 'access_token' : token }, 200
|
||||
|
@ -11,22 +11,18 @@ class HistoryGraph(Resource):
|
||||
custom_style = Style(
|
||||
background='transparent',
|
||||
plot_background='transparent',
|
||||
foreground='rgba(109, 118, 126, 0.3)',
|
||||
foreground_strong='rgba(109, 118, 126, 0.3)',
|
||||
foreground_subtle='rgba(109, 118, 126, 0.3)',
|
||||
foreground='#6c757d',
|
||||
foreground_strong='#6c757d',
|
||||
foreground_subtle='#6c757d',
|
||||
opacity='0.1',
|
||||
opacity_hover='0.2',
|
||||
transition='100ms ease-in',
|
||||
colors=('#007acc', '#749363')
|
||||
transition='0ms',
|
||||
colors=('#749363','#007acc'),
|
||||
)
|
||||
|
||||
graph = pygal.StackedLine(
|
||||
interpolate='cubic',
|
||||
interpolation_precision=3,
|
||||
#x_labels_major_every=100,
|
||||
#x_labels_major_count=500,
|
||||
graph = pygal.Line(
|
||||
stroke_style={'width': 0.4},
|
||||
show_dots=False,
|
||||
#show_dots=False,
|
||||
show_legend=False,
|
||||
fill=True,
|
||||
style=custom_style,
|
||||
@ -37,10 +33,17 @@ class HistoryGraph(Resource):
|
||||
if len(instance_count) > 0:
|
||||
graph.x_labels = [ timeago.format(instance_count[0])]
|
||||
|
||||
graph.add('Instance Count', [history['count'] for history in ctx.history.instance_history][-history_count:])
|
||||
graph.add('Client Count', [history['count'] for history in ctx.history.client_history][-history_count:])
|
||||
return { 'message' : graph.render(),
|
||||
'data_points' : len(instance_count)
|
||||
instance_counts = [history['count'] for history in ctx.history.instance_history][-history_count:]
|
||||
client_counts = [history['count'] for history in ctx.history.client_history][-history_count:]
|
||||
server_counts = [history['count'] for history in ctx.history.server_history][-history_count:]
|
||||
|
||||
graph.add('Client Count', client_counts)
|
||||
graph.add('Instance Count', instance_counts)
|
||||
return { 'message' : graph.render().replace("<title>Pygal</title>", ""),
|
||||
'data_points' : len(instance_count),
|
||||
'instance_count' : 0 if len(instance_counts) is 0 else instance_counts[-1],
|
||||
'client_count' : 0 if len(client_counts) is 0 else client_counts[-1],
|
||||
'server_count' : 0 if len(server_counts) is 0 else server_counts[-1]
|
||||
}, 200
|
||||
except Exception as e:
|
||||
return { 'message' : str(e) }, 500
|
||||
|
@ -4,6 +4,8 @@ from flask_jwt_extended import jwt_required
|
||||
from marshmallow import ValidationError
|
||||
from master.schema.instanceschema import InstanceSchema
|
||||
from master import ctx
|
||||
import json
|
||||
from netaddr import IPAddress
|
||||
|
||||
class Instance(Resource):
|
||||
def get(self, id=None):
|
||||
@ -21,6 +23,11 @@ class Instance(Resource):
|
||||
@jwt_required
|
||||
def put(self, id):
|
||||
try:
|
||||
for server in request.json['servers']:
|
||||
if 'ip' not in server or IPAddress(server['ip']).is_private() or IPAddress(server['ip']).is_loopback():
|
||||
server['ip'] = request.remote_addr
|
||||
if 'version' not in server:
|
||||
server['version'] = 'Unknown'
|
||||
instance = InstanceSchema().load(request.json)
|
||||
except ValidationError as err:
|
||||
return {'message' : err.messages }, 400
|
||||
@ -30,6 +37,11 @@ class Instance(Resource):
|
||||
@jwt_required
|
||||
def post(self):
|
||||
try:
|
||||
for server in request.json['servers']:
|
||||
if 'ip' not in server or server['ip'] == 'localhost':
|
||||
server['ip'] = request.remote_addr
|
||||
if 'version' not in server:
|
||||
server['version'] = 'Unknown'
|
||||
instance = InstanceSchema().load(request.json)
|
||||
except ValidationError as err:
|
||||
return {'message' : err.messages }, 400
|
||||
|
59
Master/master/resources/localization.py
Normal file
59
Master/master/resources/localization.py
Normal file
@ -0,0 +1,59 @@
|
||||
from flask_restful import Resource
|
||||
from flask import request, jsonify
|
||||
from flask_jwt_extended import create_access_token
|
||||
from master import app, ctx
|
||||
import datetime
|
||||
import urllib.request
|
||||
import csv
|
||||
from io import StringIO
|
||||
|
||||
class Localization(Resource):
|
||||
def list(self):
|
||||
response = urllib.request.urlopen('https://docs.google.com/spreadsheets/d/e/2PACX-1vRQjCqPvd0Xqcn86WqpFqp_lx4KKpel9O4OV13NycmV8rmqycorgJQm-8qXMfw37QJHun3pqVZFUKG-/pub?gid=0&single=true&output=csv')
|
||||
data = response.read().decode('utf-8')
|
||||
|
||||
localization = []
|
||||
csv_data = csv.DictReader(StringIO(data))
|
||||
|
||||
for language in csv_data.fieldnames[1:]:
|
||||
localization.append({
|
||||
'LocalizationName' : language,
|
||||
'LocalizationIndex' : {
|
||||
'Set' : {}
|
||||
}
|
||||
})
|
||||
|
||||
for row in csv_data:
|
||||
localization_string = row['STRING']
|
||||
count = 0
|
||||
for language in csv_data.fieldnames[1:]:
|
||||
localization[count]['LocalizationIndex']['Set'][localization_string] = row[language]
|
||||
count += 1
|
||||
|
||||
return localization, 200
|
||||
|
||||
def get(self, language_tag=None):
|
||||
response = urllib.request.urlopen('https://docs.google.com/spreadsheets/d/e/2PACX-1vRQjCqPvd0Xqcn86WqpFqp_lx4KKpel9O4OV13NycmV8rmqycorgJQm-8qXMfw37QJHun3pqVZFUKG-/pub?gid=0&single=true&output=csv')
|
||||
data = response.read().decode('utf-8')
|
||||
|
||||
csv_data = csv.DictReader(StringIO(data))
|
||||
|
||||
|
||||
if language_tag != None:
|
||||
valid_language_tag = next((l for l in csv_data.fieldnames[1:] if l == language_tag), None)
|
||||
if valid_language_tag is None:
|
||||
valid_language_tag = next((l for l in csv_data.fieldnames[1:] if l.startswith(language_tag[:2])), None)
|
||||
if valid_language_tag is None:
|
||||
valid_language_tag = 'en-US'
|
||||
localization = {
|
||||
'LocalizationName' : valid_language_tag,
|
||||
'LocalizationIndex' : {
|
||||
'Set' : {}
|
||||
}
|
||||
}
|
||||
for row in csv_data:
|
||||
localization_string = row['STRING']
|
||||
localization['LocalizationIndex']['Set'][localization_string] = row[valid_language_tag]
|
||||
return localization, 200
|
||||
else:
|
||||
return self.list()[0][0], 200
|
6
Master/master/resources/server.py
Normal file
6
Master/master/resources/server.py
Normal file
@ -0,0 +1,6 @@
|
||||
from flask_restful import Resource
|
||||
|
||||
class Server(Resource):
|
||||
"""description of class"""
|
||||
|
||||
|
@ -1,8 +1,9 @@
|
||||
from flask_restful import Resource
|
||||
from master import config
|
||||
import json
|
||||
|
||||
class Version(Resource):
|
||||
def get(self):
|
||||
config = json.load(open('./master/config/master.json'))
|
||||
return {
|
||||
'current-version-stable' : config['current-version-stable'],
|
||||
'current-version-prerelease' : config['current-version-prerelease']
|
||||
|
@ -5,9 +5,13 @@ from master.resources.instance import Instance
|
||||
from master.resources.authenticate import Authenticate
|
||||
from master.resources.version import Version
|
||||
from master.resources.history_graph import HistoryGraph
|
||||
from master.resources.localization import Localization
|
||||
from master.resources.server import Server
|
||||
|
||||
api.add_resource(Null, '/null')
|
||||
api.add_resource(Instance, '/instance/', '/instance/<string:id>')
|
||||
api.add_resource(Version, '/version')
|
||||
api.add_resource(Authenticate, '/authenticate')
|
||||
api.add_resource(HistoryGraph, '/history/', '/history/<int:history_count>')
|
||||
api.add_resource(HistoryGraph, '/history/', '/history/<int:history_count>')
|
||||
api.add_resource(Localization, '/localization/', '/localization/<string:language_tag>')
|
||||
api.add_resource(Server, '/server')
|
@ -6,4 +6,4 @@ from os import environ
|
||||
from master import app
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(host='0.0.0.0', port=80, debug=True)
|
||||
app.run(host='0.0.0.0', port=80, debug=True)
|
@ -4,19 +4,26 @@ from master.models.servermodel import ServerModel
|
||||
class ServerSchema(Schema):
|
||||
id = fields.Int(
|
||||
required=True,
|
||||
validate=validate.Range(1, 2147483647, 'invalid id')
|
||||
validate=validate.Range(0, 25525525525565535, 'invalid id')
|
||||
)
|
||||
ip = fields.Str(
|
||||
required=True
|
||||
)
|
||||
port = fields.Int(
|
||||
required=True,
|
||||
validate=validate.Range(1, 665535, 'invalid port')
|
||||
validate=validate.Range(1, 65535, 'invalid port')
|
||||
)
|
||||
version = fields.String(
|
||||
required=False,
|
||||
validate=validate.Length(0, 128, 'invalid server version')
|
||||
)
|
||||
game = fields.String(
|
||||
required=True,
|
||||
validate=validate.Length(1, 8, 'invalid game name')
|
||||
validate=validate.Length(1, 5, 'invalid game name')
|
||||
)
|
||||
hostname = fields.String(
|
||||
required=True,
|
||||
validate=validate.Length(1, 48, 'invalid hostname')
|
||||
validate=validate.Length(1, 64, 'invalid hostname')
|
||||
)
|
||||
clientnum = fields.Int(
|
||||
required=True,
|
||||
@ -28,7 +35,7 @@ class ServerSchema(Schema):
|
||||
)
|
||||
map = fields.String(
|
||||
required=True,
|
||||
validate=validate.Length(1, 32, 'invalid map name')
|
||||
validate=validate.Length(0, 64, 'invalid map name')
|
||||
)
|
||||
gametype = fields.String(
|
||||
required=True,
|
||||
|
@ -5,43 +5,60 @@
|
||||
<div class="col-12">
|
||||
<figure>
|
||||
<div id="history_graph">{{history_graph|safe}}</div>
|
||||
<figcaption class="float-right pr-3 mr-4">
|
||||
<figcaption class="float-right">
|
||||
<span id="history_graph_zoom_out" class="h4 oi oi-zoom-out text-muted" style="cursor:pointer;"></span>
|
||||
<span id="history_graph_zoom_in" class="h4 oi oi-zoom-in text-muted" style="cursor:pointer;"></span>
|
||||
</figcaption>
|
||||
<figcaption class="float-left">
|
||||
<span class="h4 text-muted">{{instance_count}} instances</span>
|
||||
<span class="h4 text-muted">— {{client_count}} clients</span>
|
||||
<span class="h4 text-muted">— {{server_count}} servers</span>
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
|
||||
</div>
|
||||
<div class="col-12">
|
||||
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script type="text/javascript" src="http://kozea.github.com/pygal.js/latest/pygal-tooltips.min.js"></script>
|
||||
<script>
|
||||
let dataPoints = {{data_points}};
|
||||
let zoomLevel = Math.ceil(dataPoints / 2);
|
||||
//console.log(dataPoints);
|
||||
<script type="text/javascript" src="http://kozea.github.com/pygal.js/latest/pygal-tooltips.min.js"></script>
|
||||
<script>
|
||||
let dataPoints = {{data_points}};
|
||||
let maxPoints = 2880;
|
||||
maxPoints = Math.min(maxPoints, dataPoints);
|
||||
let zoomLevel = Math.floor(maxPoints);
|
||||
let performingZoom = false;
|
||||
|
||||
function updateHistoryGraph() {
|
||||
$.get('/history/' + zoomLevel)
|
||||
.done(function (content) {
|
||||
$('#history_graph').html(content.message);
|
||||
dataPoints = content.data_points
|
||||
});
|
||||
function updateHistoryGraph() {
|
||||
perfomingZoom = true;
|
||||
$.get('/history/' + zoomLevel)
|
||||
.done(function (content) {
|
||||
$('#history_graph').html(content.message);
|
||||
//maxPoints = Math.min(maxPoints, dataPoints);
|
||||
perfomingZoom = false;
|
||||
});
|
||||
}
|
||||
|
||||
//setInterval(updateHistoryGraph, 30000);
|
||||
|
||||
$('#history_graph_zoom_out').click(function () {
|
||||
if (performingZoom === true) {
|
||||
return false;
|
||||
}
|
||||
setInterval(updateHistoryGraph, 30000);
|
||||
zoomLevel = Math.floor(zoomLevel * 2) <= maxPoints ? Math.floor(zoomLevel * 2) : maxPoints;
|
||||
updateHistoryGraph();
|
||||
});
|
||||
|
||||
$('#history_graph_zoom_out').click(function () {
|
||||
// console.log(zoomLevel);
|
||||
zoomLevel = zoomLevel * 2 <= 1440 ? Math.ceil(zoomLevel * 2) : dataPoints;
|
||||
updateHistoryGraph();
|
||||
});
|
||||
$('#history_graph_zoom_in').click(function () {
|
||||
if (performingZoom === true) {
|
||||
return false;
|
||||
}
|
||||
zoomLevel = zoomLevel / 2 > 2 ? Math.ceil(zoomLevel / 2) : 2;
|
||||
updateHistoryGraph();
|
||||
});
|
||||
|
||||
$('#history_graph_zoom_in').click(function () {
|
||||
// console.log(zoomLevel);
|
||||
zoomLevel = zoomLevel / 2 > 2 ? Math.ceil(zoomLevel / 2) : 2;
|
||||
updateHistoryGraph();
|
||||
});
|
||||
|
||||
</script>
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
@ -14,6 +14,18 @@
|
||||
.oi:hover {
|
||||
color: #fff !important;
|
||||
}
|
||||
.dot {
|
||||
opacity: 0;
|
||||
padding: 5px;
|
||||
}
|
||||
|
||||
.dot:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.tooltip-box {
|
||||
fill: #343a40 !important;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
@ -27,6 +39,7 @@
|
||||
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
|
||||
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
|
||||
crossorigin="anonymous"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
|
||||
{% block scripts %}{% endblock %}
|
||||
</body>
|
||||
</html>
|
||||
|
113
Master/master/templates/serverlist.html
Normal file
113
Master/master/templates/serverlist.html
Normal file
@ -0,0 +1,113 @@
|
||||
{% extends "layout.html" %}
|
||||
|
||||
{% block content %}
|
||||
<!-- todo: move this! -->
|
||||
<style>
|
||||
.server-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.modal-content, .nav-item {
|
||||
background-color: #212529;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.modal-header, .modal-footer {
|
||||
border-color: #32383e !important;
|
||||
}
|
||||
|
||||
.modal-dark button.close, a.nav-link {
|
||||
color: #fff;
|
||||
}
|
||||
</style>
|
||||
|
||||
<div class="modal modal-dark" id="serverModalCenter" tabindex="-1" role="dialog" aria-labelledby="serverModalCenterTitle" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="serverModalTitle">Modal title</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="h5" id="server_socket"></div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button id="connect_button" type="button" class="btn btn-dark">Connect</button>
|
||||
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<nav>
|
||||
<div class="nav nav-tabs" id="server_game_tabs" role="tablist">
|
||||
{% for game in games %}
|
||||
<a class="nav-item nav-link {{'active' if loop.first else ''}}" id="{{game}}_servers_tab" data-toggle="tab" href="#{{game}}_servers" role="tab" aria-controls="{{game}}_servers" aria-selected="{{'true' if loop.first else 'false' }}">{{game}}</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</nav>
|
||||
<div class="tab-content" id="server_game_tabs_content">
|
||||
{% for game, servers in games.items() %}
|
||||
|
||||
<div class="tab-pane {{'show active' if loop.first else ''}}" id="{{game}}_servers" role="tabpanel" aria-labelledby="{{game}}_servers_tab">
|
||||
|
||||
<table class="table table-dark table-striped table-hover table-responsive-lg">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Server Name</th>
|
||||
<th>Map Name</th>
|
||||
<th>Players</th>
|
||||
<th>Mode</th>
|
||||
<th class="text-center">Connect</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
|
||||
{% for server in servers %}
|
||||
|
||||
<tr class="server-row" data-toggle="modal" data-target="#serverModalCenter"
|
||||
data-ip="{{server.ip}}" data-port="{{server.port}}">
|
||||
<td data-hostname="{{server.hostname}}" class="server-hostname">{{server.hostname}}</td>
|
||||
<td data-map="{{server.map}} " class="server-map">{{server.map}}</td>
|
||||
<td data-clientnum="{{server.clientnum}}" data-maxclientnum="{{server.maxclientnum}}"
|
||||
class="server-clientnum">
|
||||
{{server.clientnum}}/{{server.maxclientnum}}
|
||||
</td>
|
||||
<td data-gametype="{{server.gametype}}" class="server-gametype">{{server.gametype}}</td>
|
||||
<td class="text-center"><span class="oi oi-play-circle"></span></td>
|
||||
</tr>
|
||||
|
||||
{% endfor %}
|
||||
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="w-100 small text-right text-muted">
|
||||
<span>Developed by RaidMax</span><br />
|
||||
<span>PRERELEASE</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script>
|
||||
$(document).ready(() => {
|
||||
$('.server-row').off('click');
|
||||
$('.server-row').on('click', function (e) {
|
||||
$('#serverModalTitle').text($(this).find('.server-hostname').text());
|
||||
$('#server_socket').text(`/connect ${$(this).data('ip')}:${$(this).data('port')}`);
|
||||
});
|
||||
|
||||
$('#connect_button').off('click');
|
||||
$('#connect_button').on('click', (e) => alert('soon...'));
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
@ -4,15 +4,32 @@ Routes and views for the flask application.
|
||||
|
||||
from datetime import datetime
|
||||
from flask import render_template
|
||||
from master import app
|
||||
from master import app, ctx
|
||||
from master.resources.history_graph import HistoryGraph
|
||||
from collections import defaultdict
|
||||
|
||||
@app.route('/')
|
||||
def home():
|
||||
_history_graph = HistoryGraph().get(500)
|
||||
_history_graph = HistoryGraph().get(2880)
|
||||
return render_template(
|
||||
'index.html',
|
||||
title='API Overview',
|
||||
history_graph = _history_graph[0]['message'],
|
||||
data_points = _history_graph[0]['data_points']
|
||||
data_points = _history_graph[0]['data_points'],
|
||||
instance_count = _history_graph[0]['instance_count'],
|
||||
client_count = _history_graph[0]['client_count'],
|
||||
server_count = _history_graph[0]['server_count']
|
||||
)
|
||||
|
||||
@app.route('/servers')
|
||||
def servers():
|
||||
servers = defaultdict(list)
|
||||
if len(ctx.instance_list.values()) > 0:
|
||||
ungrouped_servers = [server for instance in ctx.instance_list.values() for server in instance.servers]
|
||||
for server in ungrouped_servers:
|
||||
servers[server.game].append(server)
|
||||
return render_template(
|
||||
'serverlist.html',
|
||||
title = 'Server List',
|
||||
games = servers
|
||||
)
|
||||
|
@ -1,16 +1,26 @@
|
||||
aniso8601==3.0.0
|
||||
aniso8601==3.0.2
|
||||
APScheduler==3.5.3
|
||||
certifi==2018.10.15
|
||||
chardet==3.0.4
|
||||
click==6.7
|
||||
Flask==0.12.2
|
||||
Flask==1.0.2
|
||||
Flask-JWT==0.3.2
|
||||
Flask-JWT-Extended==3.8.1
|
||||
Flask-RESTful==0.3.6
|
||||
idna==2.7
|
||||
itsdangerous==0.24
|
||||
Jinja2==2.10
|
||||
MarkupSafe==1.0
|
||||
marshmallow==3.0.0b8
|
||||
pip==9.0.1
|
||||
pip==9.0.3
|
||||
psutil==5.4.8
|
||||
pygal==2.4.0
|
||||
PyJWT==1.4.2
|
||||
pytz==2018.4
|
||||
setuptools==39.0.1
|
||||
pytz==2018.7
|
||||
requests==2.20.0
|
||||
setuptools==40.5.0
|
||||
six==1.11.0
|
||||
timeago==1.0.8
|
||||
tzlocal==1.5.1
|
||||
urllib3==1.24
|
||||
Werkzeug==0.14.1
|
||||
|
21
Plugins/AutomessageFeed/AutomessageFeed.csproj
Normal file
21
Plugins/AutomessageFeed/AutomessageFeed.csproj
Normal file
@ -0,0 +1,21 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.SyndicationFeed.ReaderWriter" Version="1.0.2"/>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\SharedLibraryCore\SharedLibraryCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
<Exec Command="copy "$(TargetPath)" "$(SolutionDir)BUILD\Plugins""/>
|
||||
<Exec Command="copy "$(TargetDir)Microsoft.SyndicationFeed.ReaderWriter.dll" "$(SolutionDir)BUILD\Plugins""/>
|
||||
</Target>
|
||||
|
||||
</Project>
|
29
Plugins/AutomessageFeed/Configuration.cs
Normal file
29
Plugins/AutomessageFeed/Configuration.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
|
||||
namespace AutomessageFeed
|
||||
{
|
||||
class Configuration : IBaseConfiguration
|
||||
{
|
||||
public bool EnableFeed { get; set; }
|
||||
public string FeedUrl { get; set; }
|
||||
public int MaxFeedItems { get; set; }
|
||||
|
||||
public IBaseConfiguration Generate()
|
||||
{
|
||||
EnableFeed = Utilities.PromptBool(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_AUTOMESSAGEFEED_PROMPT_ENABLE"]);
|
||||
|
||||
if (EnableFeed)
|
||||
{
|
||||
FeedUrl = Utilities.PromptString(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_AUTOMESSAGEFEED_URL"]);
|
||||
MaxFeedItems = Utilities.PromptInt(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_AUTOMESSAGEFEED_PROMPT_MAXITEMS"],
|
||||
Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_AUTOMESSAGEFEED_PROMPT_MAXITEMS_DESC"],
|
||||
0, int.MaxValue, 0);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public string Name() => "AutomessageFeedConfiguration";
|
||||
}
|
||||
}
|
85
Plugins/AutomessageFeed/Plugin.cs
Normal file
85
Plugins/AutomessageFeed/Plugin.cs
Normal file
@ -0,0 +1,85 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.SyndicationFeed.Rss;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using System.Xml;
|
||||
using Microsoft.SyndicationFeed;
|
||||
using System.Collections.Generic;
|
||||
using SharedLibraryCore.Helpers;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace AutomessageFeed
|
||||
{
|
||||
public class Plugin : IPlugin
|
||||
{
|
||||
public string Name => "Automessage Feed";
|
||||
|
||||
public float Version => (float)Utilities.GetVersionAsDouble();
|
||||
|
||||
public string Author => "RaidMax";
|
||||
|
||||
private Configuration _configuration;
|
||||
private int _currentFeedItem;
|
||||
|
||||
private async Task<string> GetNextFeedItem(Server server)
|
||||
{
|
||||
var items = new List<string>();
|
||||
|
||||
using (var reader = XmlReader.Create(_configuration.FeedUrl, new XmlReaderSettings() { Async = true }))
|
||||
{
|
||||
var feedReader = new RssFeedReader(reader);
|
||||
|
||||
while (await feedReader.Read())
|
||||
{
|
||||
switch (feedReader.ElementType)
|
||||
{
|
||||
case SyndicationElementType.Item:
|
||||
var item = await feedReader.ReadItem();
|
||||
items.Add(Regex.Replace(item.Title, @"\<.+\>.*\</.+\>", ""));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (_currentFeedItem < items.Count && (_configuration.MaxFeedItems == 0 || _currentFeedItem < _configuration.MaxFeedItems))
|
||||
{
|
||||
_currentFeedItem++;
|
||||
return items[_currentFeedItem - 1];
|
||||
}
|
||||
|
||||
_currentFeedItem = 0;
|
||||
return Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_AUTOMESSAGEFEED_NO_ITEMS"];
|
||||
}
|
||||
|
||||
public Task OnEventAsync(GameEvent E, Server S)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task OnLoadAsync(IManager manager)
|
||||
{
|
||||
var cfg = new BaseConfigurationHandler<Configuration>("AutomessageFeedPluginSettings");
|
||||
if (cfg.Configuration() == null)
|
||||
{
|
||||
cfg.Set((Configuration)new Configuration().Generate());
|
||||
await cfg.Save();
|
||||
}
|
||||
|
||||
_configuration = cfg.Configuration();
|
||||
|
||||
manager.GetMessageTokens().Add(new MessageToken("FEED", GetNextFeedItem));
|
||||
}
|
||||
|
||||
public Task OnTickAsync(Server S)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task OnUnloadAsync()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
14
Plugins/IW4ScriptCommands/CommandInfo.cs
Normal file
14
Plugins/IW4ScriptCommands/CommandInfo.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace IW4ScriptCommands
|
||||
{
|
||||
class CommandInfo
|
||||
{
|
||||
public string Command { get; set; }
|
||||
public int ClientNumber { get; set; }
|
||||
public List<string> CommandArguments { get; set; } = new List<string>();
|
||||
public override string ToString() => $"{Command};{ClientNumber},{string.Join(',', CommandArguments)}";
|
||||
}
|
||||
}
|
200
Plugins/IW4ScriptCommands/Commands/Balance.cs
Normal file
200
Plugins/IW4ScriptCommands/Commands/Balance.cs
Normal file
@ -0,0 +1,200 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4ScriptCommands.Commands
|
||||
{
|
||||
class Balance
|
||||
{
|
||||
private class TeamAssignment
|
||||
{
|
||||
public IW4MAdmin.Plugins.Stats.IW4Info.Team CurrentTeam { get; set; }
|
||||
public int Num { get; set; }
|
||||
public IW4MAdmin.Plugins.Stats.Models.EFClientStatistics Stats { get; set; }
|
||||
}
|
||||
|
||||
public static string GetTeamAssignments(EFClient client, bool isDisconnect, Server server, string teamsString = "")
|
||||
{
|
||||
var scriptClientTeams = teamsString.Split(';', StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(c => c.Split(','))
|
||||
.Select(c => new TeamAssignment()
|
||||
{
|
||||
CurrentTeam = (IW4MAdmin.Plugins.Stats.IW4Info.Team)Enum.Parse(typeof(IW4MAdmin.Plugins.Stats.IW4Info.Team), c[1]),
|
||||
Num = server.GetClientsAsList().FirstOrDefault(p => p.ClientNumber == Int32.Parse(c[0]))?.ClientNumber ?? -1,
|
||||
Stats = IW4MAdmin.Plugins.Stats.Plugin.Manager.GetClientStats(server.Clients.FirstOrDefault(p => p.ClientNumber == Int32.Parse(c[0])).ClientId, server.EndPoint)
|
||||
})
|
||||
.ToList();
|
||||
|
||||
// at least one team is full so we can't balance
|
||||
if (scriptClientTeams.Count(ct => ct.CurrentTeam == IW4MAdmin.Plugins.Stats.IW4Info.Team.Axis) >= Math.Floor(server.MaxClients / 2.0)
|
||||
|| scriptClientTeams.Count(ct => ct.CurrentTeam == IW4MAdmin.Plugins.Stats.IW4Info.Team.Allies) >= Math.Floor(server.MaxClients / 2.0))
|
||||
{
|
||||
// E.Origin?.Tell(Utilities.CurrentLocalization.LocalizationIndex["COMMANDS_BALANCE_FAIL"]);
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
List<string> teamAssignments = new List<string>();
|
||||
|
||||
var _c = server.GetClientsAsList();
|
||||
if (isDisconnect && client != null)
|
||||
{
|
||||
_c = _c.Where(c => c.ClientNumber != client.ClientNumber).ToList();
|
||||
}
|
||||
|
||||
var activeClients = _c.Select(c => new TeamAssignment()
|
||||
{
|
||||
Num = c.ClientNumber,
|
||||
Stats = IW4MAdmin.Plugins.Stats.Plugin.Manager.GetClientStats(c.ClientId, server.EndPoint),
|
||||
CurrentTeam = IW4MAdmin.Plugins.Stats.Plugin.Manager.GetClientStats(c.ClientId, server.EndPoint).Team
|
||||
})
|
||||
.Where(c => scriptClientTeams.FirstOrDefault(sc => sc.Num == c.Num)?.CurrentTeam != IW4MAdmin.Plugins.Stats.IW4Info.Team.Spectator)
|
||||
.Where(c => c.CurrentTeam != scriptClientTeams.FirstOrDefault(p => p.Num == c.Num)?.CurrentTeam)
|
||||
.OrderByDescending(c => c.Stats.Performance)
|
||||
.ToList();
|
||||
|
||||
var alliesTeam = scriptClientTeams
|
||||
.Where(c => c.CurrentTeam == IW4MAdmin.Plugins.Stats.IW4Info.Team.Allies)
|
||||
.Where(c => activeClients.Count(t => t.Num == c.Num) == 0)
|
||||
.ToList();
|
||||
|
||||
var axisTeam = scriptClientTeams
|
||||
.Where(c => c.CurrentTeam == IW4MAdmin.Plugins.Stats.IW4Info.Team.Axis)
|
||||
.Where(c => activeClients.Count(t => t.Num == c.Num) == 0)
|
||||
.ToList();
|
||||
|
||||
while (activeClients.Count() > 0)
|
||||
{
|
||||
int teamSizeDifference = alliesTeam.Count - axisTeam.Count;
|
||||
double performanceDisparity = alliesTeam.Count > 0 ? alliesTeam.Average(t => t.Stats.Performance) : 0 -
|
||||
axisTeam.Count > 0 ? axisTeam.Average(t => t.Stats.Performance) : 0;
|
||||
|
||||
if (teamSizeDifference == 0)
|
||||
{
|
||||
if (performanceDisparity == 0)
|
||||
{
|
||||
alliesTeam.Add(activeClients.First());
|
||||
activeClients.RemoveAt(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (performanceDisparity > 0)
|
||||
{
|
||||
axisTeam.Add(activeClients.First());
|
||||
activeClients.RemoveAt(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
alliesTeam.Add(activeClients.First());
|
||||
activeClients.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (teamSizeDifference > 0)
|
||||
{
|
||||
if (performanceDisparity > 0)
|
||||
{
|
||||
axisTeam.Add(activeClients.First());
|
||||
activeClients.RemoveAt(0);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
axisTeam.Add(activeClients.Last());
|
||||
activeClients.RemoveAt(activeClients.Count - 1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (performanceDisparity > 0)
|
||||
{
|
||||
alliesTeam.Add(activeClients.First());
|
||||
activeClients.RemoveAt(0);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
alliesTeam.Add(activeClients.Last());
|
||||
activeClients.RemoveAt(activeClients.Count - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
alliesTeam = alliesTeam.OrderByDescending(t => t.Stats.Performance)
|
||||
.ToList();
|
||||
|
||||
axisTeam = axisTeam.OrderByDescending(t => t.Stats.Performance)
|
||||
.ToList();
|
||||
|
||||
while (Math.Abs(alliesTeam.Count - axisTeam.Count) > 1)
|
||||
{
|
||||
int teamSizeDifference = alliesTeam.Count - axisTeam.Count;
|
||||
double performanceDisparity = alliesTeam.Count > 0 ? alliesTeam.Average(t => t.Stats.Performance) : 0 -
|
||||
axisTeam.Count > 0 ? axisTeam.Average(t => t.Stats.Performance) : 0;
|
||||
|
||||
if (teamSizeDifference > 0)
|
||||
{
|
||||
if (performanceDisparity > 0)
|
||||
{
|
||||
axisTeam.Add(alliesTeam.First());
|
||||
alliesTeam.RemoveAt(0);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
axisTeam.Add(alliesTeam.Last());
|
||||
alliesTeam.RemoveAt(axisTeam.Count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
if (performanceDisparity > 0)
|
||||
{
|
||||
alliesTeam.Add(axisTeam.Last());
|
||||
axisTeam.RemoveAt(axisTeam.Count - 1);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
alliesTeam.Add(axisTeam.First());
|
||||
axisTeam.RemoveAt(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var assignment in alliesTeam)
|
||||
{
|
||||
teamAssignments.Add($"{assignment.Num},2");
|
||||
assignment.Stats.Team = IW4MAdmin.Plugins.Stats.IW4Info.Team.Allies;
|
||||
}
|
||||
|
||||
foreach (var assignment in axisTeam)
|
||||
{
|
||||
teamAssignments.Add($"{assignment.Num},3");
|
||||
assignment.Stats.Team = IW4MAdmin.Plugins.Stats.IW4Info.Team.Axis;
|
||||
}
|
||||
|
||||
//if (alliesTeam.Count(ac => scriptClientTeams.First(sc => sc.Num == ac.Num).CurrentTeam != ac.CurrentTeam) == 0 &&
|
||||
// axisTeam.Count(ac => scriptClientTeams.First(sc => sc.Num == ac.Num).CurrentTeam != ac.CurrentTeam) == 0)
|
||||
//{
|
||||
// //E.Origin.Tell(Utilities.CurrentLocalization.LocalizationIndex["COMMANDS_BALANCE_FAIL_BALANCED"]);
|
||||
// return string.Empty;
|
||||
//}
|
||||
|
||||
//if (E.Origin?.Level > Player.Permission.Administrator)
|
||||
//{
|
||||
// E.Origin.Tell($"Allies Elo: {(alliesTeam.Count > 0 ? alliesTeam.Average(t => t.Stats.Performance) : 0)}");
|
||||
// E.Origin.Tell($"Axis Elo: {(axisTeam.Count > 0 ? axisTeam.Average(t => t.Stats.Performance) : 0)}");
|
||||
//}
|
||||
|
||||
//E.Origin.Tell("Balance command sent");
|
||||
string args = string.Join(",", teamAssignments);
|
||||
return args;
|
||||
}
|
||||
}
|
||||
}
|
54
Plugins/IW4ScriptCommands/GscApiController.cs
Normal file
54
Plugins/IW4ScriptCommands/GscApiController.cs
Normal file
@ -0,0 +1,54 @@
|
||||
using IW4ScriptCommands.Commands;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WebfrontCore.Controllers.API
|
||||
{
|
||||
[Route("api/gsc/[action]")]
|
||||
public class GscApiController : ApiController
|
||||
{
|
||||
[HttpGet("{networkId}")]
|
||||
public IActionResult ClientInfo(string networkId)
|
||||
{
|
||||
var clientInfo = Manager.GetActiveClients()
|
||||
.FirstOrDefault(c => c.NetworkId == networkId.ConvertLong());
|
||||
|
||||
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("");
|
||||
}
|
||||
|
||||
[HttpGet("{networkId}")]
|
||||
public IActionResult GetTeamAssignments(string networkId, int serverId, string teams = "", bool isDisconnect = false)
|
||||
{
|
||||
return Unauthorized();
|
||||
|
||||
var client = Manager.GetActiveClients()
|
||||
.FirstOrDefault(c => c.NetworkId == networkId.ConvertLong());
|
||||
|
||||
var server = Manager.GetServers().First(c => c.EndPoint == serverId);
|
||||
|
||||
teams = teams ?? string.Empty;
|
||||
|
||||
string assignments = Balance.GetTeamAssignments(client, isDisconnect, server, teams);
|
||||
|
||||
return Content(assignments);
|
||||
}
|
||||
}
|
||||
}
|
25
Plugins/IW4ScriptCommands/IW4ScriptCommands.csproj
Normal file
25
Plugins/IW4ScriptCommands/IW4ScriptCommands.csproj
Normal file
@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<RuntimeFrameworkVersion>2.2.2</RuntimeFrameworkVersion>
|
||||
<ApplicationIcon />
|
||||
<StartupObject />
|
||||
<Configurations>Debug;Release;Prerelease</Configurations>
|
||||
</PropertyGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
<Exec Command="copy "$(TargetPath)" "$(SolutionDir)BUILD\Plugins"" />
|
||||
</Target>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\SharedLibraryCore\SharedLibraryCore.csproj" />
|
||||
<ProjectReference Include="..\Stats\Stats.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Update="Microsoft.NETCore.App" Version="2.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
49
Plugins/IW4ScriptCommands/Plugin.cs
Normal file
49
Plugins/IW4ScriptCommands/Plugin.cs
Normal file
@ -0,0 +1,49 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4ScriptCommands
|
||||
{
|
||||
class Plugin : IPlugin
|
||||
{
|
||||
public string Name => "IW4 Script Commands";
|
||||
|
||||
public float Version => 1.0f;
|
||||
|
||||
public string Author => "RaidMax";
|
||||
|
||||
public Task OnEventAsync(GameEvent E, Server S)
|
||||
{
|
||||
if (E.Type == GameEvent.EventType.Start)
|
||||
{
|
||||
return S.SetDvarAsync("sv_iw4madmin_serverid", S.EndPoint);
|
||||
}
|
||||
|
||||
if (E.Type == GameEvent.EventType.Warn)
|
||||
{
|
||||
return S.SetDvarAsync("sv_iw4madmin_command", new CommandInfo()
|
||||
{
|
||||
ClientNumber = E.Target.ClientNumber,
|
||||
Command = "alert",
|
||||
CommandArguments = new List<string>()
|
||||
{
|
||||
"Warning",
|
||||
"ui_mp_nukebomb_timer",
|
||||
E.Data
|
||||
}
|
||||
}.ToString());
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task OnLoadAsync(IManager manager) => Task.CompletedTask;
|
||||
|
||||
public Task OnTickAsync(Server S) => Task.CompletedTask;
|
||||
|
||||
public Task OnUnloadAsync() => Task.CompletedTask;
|
||||
}
|
||||
}
|
@ -1,37 +1,40 @@
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Plugins.Login.Commands
|
||||
{
|
||||
public class CLogin : Command
|
||||
{
|
||||
public CLogin() : base("login", "login using password", "l", Player.Permission.Trusted, false, new CommandArgument[]
|
||||
public CLogin() : base("login", Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_LOGIN_COMMANDS_LOGIN_DESC"], "li", EFClient.Permission.Trusted, false, new CommandArgument[]
|
||||
{
|
||||
new CommandArgument()
|
||||
{
|
||||
Name = "password",
|
||||
Name = Utilities.CurrentLocalization.LocalizationIndex["COMMANDS_ARGS_PASSWORD"],
|
||||
Required = true
|
||||
}
|
||||
}){ }
|
||||
})
|
||||
{ }
|
||||
|
||||
public override async Task ExecuteAsync(GameEvent E)
|
||||
{
|
||||
var client = E.Owner.Manager.GetPrivilegedClients()[E.Origin.ClientId];
|
||||
string[] hashedPassword = await Task.FromResult(SharedLibraryCore.Helpers.Hashing.Hash(E.Data, client.PasswordSalt));
|
||||
bool success = E.Owner.Manager.TokenAuthenticator.AuthorizeToken(E.Origin.NetworkId, E.Data);
|
||||
|
||||
if (hashedPassword[0] == client.Password)
|
||||
if (!success)
|
||||
{
|
||||
string[] hashedPassword = await Task.FromResult(SharedLibraryCore.Helpers.Hashing.Hash(E.Data, client.PasswordSalt));
|
||||
success = hashedPassword[0] == client.Password;
|
||||
}
|
||||
|
||||
if (success)
|
||||
{
|
||||
Plugin.AuthorizedClients[E.Origin.ClientId] = true;
|
||||
await E.Origin.Tell("You are now logged in");
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
await E.Origin.Tell("Your password is incorrect");
|
||||
}
|
||||
_ = success ?
|
||||
E.Origin.Tell(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_LOGIN_COMMANDS_LOGIN_SUCCESS"]) :
|
||||
E.Origin.Tell(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_LOGIN_COMMANDS_LOGIN_FAIL"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<RuntimeFrameworkVersion>2.2.2</RuntimeFrameworkVersion>
|
||||
<ApplicationIcon />
|
||||
<StartupObject />
|
||||
<PackageId>RaidMax.IW4MAdmin.Plugins.Login</PackageId>
|
||||
@ -20,6 +21,10 @@
|
||||
<ProjectReference Include="..\..\SharedLibraryCore\SharedLibraryCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Update="Microsoft.NETCore.App" Version="2.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
<Exec Command="copy "$(TargetPath)" "$(SolutionDir)BUILD\Plugins"" />
|
||||
</Target>
|
||||
|
@ -3,6 +3,7 @@ using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Exceptions;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
|
||||
@ -21,12 +22,13 @@ namespace IW4MAdmin.Plugins.Login
|
||||
|
||||
public Task OnEventAsync(GameEvent E, Server S)
|
||||
{
|
||||
if (E.Remote || Config.RequirePrivilegedClientLogin == false)
|
||||
if (E.IsRemote || Config.RequirePrivilegedClientLogin == false)
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (E.Type == GameEvent.EventType.Connect)
|
||||
{
|
||||
AuthorizedClients.TryAdd(E.Origin.ClientId, false);
|
||||
E.Origin.SetAdditionalProperty("IsLoggedIn", false);
|
||||
}
|
||||
|
||||
if (E.Type == GameEvent.EventType.Disconnect)
|
||||
@ -36,18 +38,28 @@ namespace IW4MAdmin.Plugins.Login
|
||||
|
||||
if (E.Type == GameEvent.EventType.Command)
|
||||
{
|
||||
if (E.Origin.Level < SharedLibraryCore.Objects.Player.Permission.Moderator)
|
||||
if (E.Origin.Level < EFClient.Permission.Moderator ||
|
||||
E.Origin.Level == EFClient.Permission.Console)
|
||||
return Task.CompletedTask;
|
||||
|
||||
E.Owner.Manager.GetPrivilegedClients().TryGetValue(E.Origin.ClientId, out EFClient client);
|
||||
|
||||
if (((Command)E.Extra).Name == new SharedLibraryCore.Commands.CSetPassword().Name &&
|
||||
E.Owner.Manager.GetPrivilegedClients()[E.Origin.ClientId].Password == null)
|
||||
client?.Password == null)
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (((Command)E.Extra).Name == new Commands.CLogin().Name)
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (!AuthorizedClients[E.Origin.ClientId])
|
||||
throw new AuthorizationException("not logged in");
|
||||
{
|
||||
throw new AuthorizationException(Utilities.CurrentLocalization.LocalizationIndex["PLUGINS_LOGIN_AUTH"]);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
E.Origin.SetAdditionalProperty("IsLoggedIn", true);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
@ -67,12 +79,8 @@ namespace IW4MAdmin.Plugins.Login
|
||||
Config = cfg.Configuration();
|
||||
}
|
||||
|
||||
public Task OnTickAsync(Server S) => Utilities.CompletedTask;
|
||||
public Task OnTickAsync(Server S) => Task.CompletedTask;
|
||||
|
||||
public Task OnUnloadAsync()
|
||||
{
|
||||
AuthorizedClients.Clear();
|
||||
return Utilities.CompletedTask;
|
||||
}
|
||||
public Task OnUnloadAsync() => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
@ -16,14 +16,16 @@ namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
{
|
||||
OffensiveWords = new List<string>()
|
||||
{
|
||||
"nigger",
|
||||
"nigga",
|
||||
"fuck"
|
||||
@"\s*n+.*i+.*g+.*e+.*r+\s*",
|
||||
@"\s*n+.*i+.*g+.*a+\s*",
|
||||
@"\s*f+u+.*c+.*k+.*\s*"
|
||||
};
|
||||
|
||||
EnableProfanityDeterment = Utilities.PromptBool("Enable profanity deterring");
|
||||
ProfanityWarningMessage = "Please do not use profanity on this server";
|
||||
ProfanityKickMessage = "Excessive use of profanity";
|
||||
var loc = Utilities.CurrentLocalization.LocalizationIndex;
|
||||
|
||||
EnableProfanityDeterment = Utilities.PromptBool(loc["PLUGINS_PROFANITY_SETUP_ENABLE"]);
|
||||
ProfanityWarningMessage = loc["PLUGINS_PROFANITY_WARNMSG"];
|
||||
ProfanityKickMessage = loc["PLUGINS_PROFANITY_KICKMSG"];
|
||||
KickAfterInfringementCount = 2;
|
||||
|
||||
return this;
|
||||
|
@ -1,11 +1,12 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using SharedLibraryCore;
|
||||
using SharedLibraryCore.Configuration;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
|
||||
namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
{
|
||||
@ -20,12 +21,11 @@ namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
BaseConfigurationHandler<Configuration> Settings;
|
||||
ConcurrentDictionary<int, Tracking> ProfanityCounts;
|
||||
IManager Manager;
|
||||
Task CompletedTask = Task.FromResult(false);
|
||||
|
||||
public async Task OnEventAsync(GameEvent E, Server S)
|
||||
public Task OnEventAsync(GameEvent E, Server S)
|
||||
{
|
||||
if (!Settings.Configuration().EnableProfanityDeterment)
|
||||
return;
|
||||
return Task.CompletedTask;
|
||||
|
||||
if (E.Type == GameEvent.EventType.Connect)
|
||||
{
|
||||
@ -34,6 +34,22 @@ namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
S.Logger.WriteWarning("Could not add client to profanity tracking");
|
||||
}
|
||||
|
||||
var objectionalWords = Settings.Configuration().OffensiveWords;
|
||||
bool containsObjectionalWord = objectionalWords.FirstOrDefault(w => E.Origin.Name.ToLower().Contains(w)) != null;
|
||||
|
||||
// we want to run regex against it just incase
|
||||
if (!containsObjectionalWord)
|
||||
{
|
||||
foreach (string word in objectionalWords)
|
||||
{
|
||||
containsObjectionalWord |= Regex.IsMatch(E.Origin.Name.ToLower(), word, RegexOptions.IgnoreCase);
|
||||
}
|
||||
}
|
||||
|
||||
if (containsObjectionalWord)
|
||||
{
|
||||
E.Origin.Kick(Settings.Configuration().ProfanityKickMessage, Utilities.IW4MAdminClient(E.Owner));
|
||||
};
|
||||
}
|
||||
|
||||
if (E.Type == GameEvent.EventType.Disconnect)
|
||||
@ -47,30 +63,36 @@ namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
if (E.Type == GameEvent.EventType.Say)
|
||||
{
|
||||
var objectionalWords = Settings.Configuration().OffensiveWords;
|
||||
bool containsObjectionalWord = objectionalWords.FirstOrDefault(w => E.Data.ToLower().Contains(w)) != null;
|
||||
bool containsObjectionalWord = false;
|
||||
|
||||
foreach (string word in objectionalWords)
|
||||
{
|
||||
containsObjectionalWord |= Regex.IsMatch(E.Data.ToLower(), word, RegexOptions.IgnoreCase);
|
||||
|
||||
// break out early because there's at least one objectional word
|
||||
if (containsObjectionalWord)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (containsObjectionalWord)
|
||||
{
|
||||
var clientProfanity = ProfanityCounts[E.Origin.ClientId];
|
||||
if (clientProfanity.Infringements >= Settings.Configuration().KickAfterInfringementCount)
|
||||
{
|
||||
await clientProfanity.Client.Kick(Settings.Configuration().ProfanityKickMessage, new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
});
|
||||
clientProfanity.Client.Kick(Settings.Configuration().ProfanityKickMessage, Utilities.IW4MAdminClient(E.Owner));
|
||||
}
|
||||
|
||||
else if (clientProfanity.Infringements < Settings.Configuration().KickAfterInfringementCount)
|
||||
{
|
||||
clientProfanity.Infringements++;
|
||||
|
||||
await clientProfanity.Client.Warn(Settings.Configuration().ProfanityWarningMessage, new Player()
|
||||
{
|
||||
ClientId = 1
|
||||
});
|
||||
clientProfanity.Client.Warn(Settings.Configuration().ProfanityWarningMessage, Utilities.IW4MAdminClient(E.Owner));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public async Task OnLoadAsync(IManager manager)
|
||||
@ -87,8 +109,8 @@ namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
Manager = manager;
|
||||
}
|
||||
|
||||
public Task OnTickAsync(Server S) => CompletedTask;
|
||||
public Task OnTickAsync(Server S) => Task.CompletedTask;
|
||||
|
||||
public Task OnUnloadAsync() => CompletedTask;
|
||||
public Task OnUnloadAsync() => Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
@ -1,8 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFramework>netcoreapp2.0</TargetFramework>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<RuntimeFrameworkVersion>2.2.2</RuntimeFrameworkVersion>
|
||||
<ApplicationIcon />
|
||||
<StartupObject />
|
||||
<PackageId>RaidMax.IW4MAdmin.Plugins.ProfanityDeterment</PackageId>
|
||||
@ -18,6 +19,10 @@
|
||||
<ProjectReference Include="..\..\SharedLibraryCore\SharedLibraryCore.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Update="Microsoft.NETCore.App" Version="2.2.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
|
||||
<Exec Command="copy "$(TargetPath)" "$(SolutionDir)BUILD\Plugins"" />
|
||||
</Target>
|
||||
|
@ -1,16 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using SharedLibraryCore.Database.Models;
|
||||
using SharedLibraryCore.Objects;
|
||||
|
||||
namespace IW4MAdmin.Plugins.ProfanityDeterment
|
||||
{
|
||||
class Tracking
|
||||
{
|
||||
public Player Client { get; private set; }
|
||||
public EFClient Client { get; private set; }
|
||||
public int Infringements { get; set; }
|
||||
|
||||
public Tracking(Player client)
|
||||
public Tracking(EFClient client)
|
||||
{
|
||||
Client = client;
|
||||
Infringements = 0;
|
||||
|
38
Plugins/ScriptPlugins/ParserCoD4x.js
Normal file
38
Plugins/ScriptPlugins/ParserCoD4x.js
Normal file
@ -0,0 +1,38 @@
|
||||
var rconParser;
|
||||
var eventParser;
|
||||
|
||||
var plugin = {
|
||||
author: 'FrenchFry, RaidMax',
|
||||
version: 0.3,
|
||||
name: 'CoD4x Parser',
|
||||
isParser: true,
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
rconParser = manager.GenerateDynamicRConParser();
|
||||
eventParser = manager.GenerateDynamicEventParser();
|
||||
|
||||
rconParser.Configuration.Status.Pattern = '^ *([0-9]+) +-?([0-9]+) +((?:[A-Z]+|[0-9]+)) +((?:[a-z]|[0-9]){16}|(?:[a-z]|[0-9]){32}|bot[0-9]+|(?:[0-9]+)) *(.{0,32}) +([0-9]+) +(\\d+\\.\\d+\\.\\d+.\\d+\\:-*\\d{1,5}|0+.0+:-*\\d{1,5}|loopback) +(-*[0-9]+) +([0-9]+) *$'
|
||||
rconParser.Configuration.Status.AddMapping(104, 6); // RConName
|
||||
rconParser.Configuration.Status.AddMapping(105, 8); // RConIPAddress
|
||||
|
||||
rconParser.Configuration.Dvar.Pattern = '^"(.+)" is: "(.+)?" default: "(.+)?" info: "(.+)?"$';
|
||||
rconParser.Configuration.Dvar.AddMapping(109, 2); // DVAR latched value
|
||||
rconParser.Configuration.Dvar.AddMapping(110, 4); // dvar info
|
||||
rconParser.Version = 'CoD4 X 1.8 win_mingw-x86 build 2055 May 2 2017';
|
||||
rconParser.GameName = 1; // IW3
|
||||
|
||||
eventParser.Configuration.GameDirectory = 'main';
|
||||
eventParser.Version = 'CoD4 X 1.8 win_mingw-x86 build 2055 May 2 2017';
|
||||
eventParser.GameName = 1; // IW3
|
||||
eventParser.URLProtocolFormat = 'cod4://{{ip}}:{{port}}';
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
36
Plugins/ScriptPlugins/ParserIW4x.js
Normal file
36
Plugins/ScriptPlugins/ParserIW4x.js
Normal file
@ -0,0 +1,36 @@
|
||||
var rconParser;
|
||||
var eventParser;
|
||||
|
||||
var plugin = {
|
||||
author: 'RaidMax',
|
||||
version: 0.3,
|
||||
name: 'IW4 Parser',
|
||||
isParser: true,
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
rconParser = manager.GenerateDynamicRConParser();
|
||||
eventParser = manager.GenerateDynamicEventParser();
|
||||
|
||||
rconParser.Configuration.CommandPrefixes.Tell = 'tellraw {0} {1}';
|
||||
rconParser.Configuration.CommandPrefixes.Say = 'sayraw {0}';
|
||||
rconParser.Configuration.CommandPrefixes.Kick = 'clientkick {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.Ban = 'clientkick {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.TempBan = 'tempbanclient {0} "{1}"';
|
||||
eventParser.Configuration.GameDirectory = 'userraw';
|
||||
|
||||
rconParser.Version = 'IW4x (v0.6.0)';
|
||||
rconParser.GameName = 2; // IW4x
|
||||
eventParser.Version = 'IW4x (v0.6.0)';
|
||||
eventParser.GameName = 2; // IW4x
|
||||
eventParser.URLProtocolFormat = 'iw4x://{{ip}}:{{port}}';
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
50
Plugins/ScriptPlugins/ParserPT6.js
Normal file
50
Plugins/ScriptPlugins/ParserPT6.js
Normal file
@ -0,0 +1,50 @@
|
||||
var rconParser;
|
||||
var eventParser;
|
||||
|
||||
var plugin = {
|
||||
author: 'RaidMax',
|
||||
version: 0.2,
|
||||
name: 'Plutonium T6 Parser',
|
||||
isParser: true,
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
rconParser = manager.GenerateDynamicRConParser();
|
||||
eventParser = manager.GenerateDynamicEventParser();
|
||||
|
||||
rconParser.Configuration.CommandPrefixes.Tell = 'tell {0} {1}';
|
||||
rconParser.Configuration.CommandPrefixes.Say = 'say {0}';
|
||||
rconParser.Configuration.CommandPrefixes.Kick = 'clientkick_for_reason {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.Ban = 'clientkick_for_reason {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.TempBan = 'clientkick_for_reason {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.RConGetDvar = '\xff\xff\xff\xffrcon {0} get {1}';
|
||||
|
||||
rconParser.Configuration.Dvar.Pattern = '^(.+) is "(.+)?"$';
|
||||
rconParser.Configuration.Dvar.AddMapping(106, 1);
|
||||
rconParser.Configuration.Dvar.AddMapping(107, 2);
|
||||
rconParser.Configuration.WaitForResponse = false;
|
||||
|
||||
rconParser.Configuration.Status.Pattern = '^ *([0-9]+) +([0-9]+) +(.+) +((?:[A-Z]+|[0-9]+)) +((?:[A-Z]|[0-9]){8,16}) +(.{0,16}) +([0-9]+) +(\\d+\\.\\d+\\.\\d+\\.\\d+\\:-?\\d{1,5}|0+\\.0+:-?\\d{1,5}|loopback) +(-?[0-9]+) +([0-9]+) *$'
|
||||
rconParser.Configuration.Status.AddMapping(100, 1);
|
||||
rconParser.Configuration.Status.AddMapping(101, 2);
|
||||
rconParser.Configuration.Status.AddMapping(102, 4);
|
||||
rconParser.Configuration.Status.AddMapping(103, 5);
|
||||
rconParser.Configuration.Status.AddMapping(104, 6);
|
||||
rconParser.Configuration.Status.AddMapping(105, 8);
|
||||
|
||||
eventParser.Configuration.GameDirectory = 't6r\\data';
|
||||
|
||||
rconParser.Version = 'Call of Duty Multiplayer - Ship COD_T6_S MP build 1.0.44 CL(1759941) CODPCAB2 CEG Fri May 9 19:19:19 2014 win-x86 813e66d5';
|
||||
rconParser.GameName = 7; // T6
|
||||
eventParser.Version = 'Call of Duty Multiplayer - Ship COD_T6_S MP build 1.0.44 CL(1759941) CODPCAB2 CEG Fri May 9 19:19:19 2014 win-x86 813e66d5';
|
||||
eventParser.GameName = 7; // T6
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
34
Plugins/ScriptPlugins/ParserRektT5M.js
Normal file
34
Plugins/ScriptPlugins/ParserRektT5M.js
Normal file
@ -0,0 +1,34 @@
|
||||
var rconParser;
|
||||
var eventParser;
|
||||
|
||||
var plugin = {
|
||||
author: 'RaidMax',
|
||||
version: 0.1,
|
||||
name: 'RektT5m Parser',
|
||||
isParser: true,
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
rconParser = manager.GenerateDynamicRConParser();
|
||||
eventParser = manager.GenerateDynamicEventParser();
|
||||
|
||||
eventParser.Configuration.GameDirectory = 'data';
|
||||
|
||||
rconParser.Configuration.CommandPrefixes.RConResponse = '\xff\xff\xff\xff\1print';
|
||||
rconParser.Configuration.CommandPrefixes.Tell = 'tell {0} {1}';
|
||||
rconParser.Configuration.CommandPrefixes.RConGetInfo = undefined;
|
||||
|
||||
rconParser.Version = 'Call of Duty Multiplayer - Ship COD_T5_S MP build 7.0.189 CL(1022875) CODPCAB-V64 CEG Wed Nov 02 18:02:23 2011 win-x86';
|
||||
rconParser.GameName = 6; // T5
|
||||
eventParser.Version = 'Call of Duty Multiplayer - Ship COD_T5_S MP build 7.0.189 CL(1022875) CODPCAB-V64 CEG Wed Nov 02 18:02:23 2011 win-x86';
|
||||
eventParser.GameName = 6; // T5
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
43
Plugins/ScriptPlugins/ParserTeknoMW3.js
Normal file
43
Plugins/ScriptPlugins/ParserTeknoMW3.js
Normal file
@ -0,0 +1,43 @@
|
||||
var rconParser;
|
||||
var eventParser;
|
||||
|
||||
var plugin = {
|
||||
author: 'RaidMax',
|
||||
version: 0.2,
|
||||
name: 'Tekno MW3 Parser',
|
||||
isParser: true,
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
rconParser = manager.GenerateDynamicRConParser();
|
||||
eventParser = manager.GenerateDynamicEventParser();
|
||||
|
||||
rconParser.Configuration.Status.Pattern = '^ *([0-9]+) +([0-9]+) +((?:[A-Z]+|[0-9]+)) +((?:[A-Z]|[0-9]){16,32})\t +(.{0,16}) +([0-9]+) +(\\d+\\.\\d+\\.\\d+\\.\\d+\\:-?\\d{1,5}|0+\\.0+\\:-?\\d{1,5}|loopback) *$';
|
||||
rconParser.Configuration.Status.AddMapping(104, 5); // RConName
|
||||
rconParser.Configuration.Status.AddMapping(103, 4); // RConNetworkId
|
||||
rconParser.Configuration.CommandPrefixes.RConGetInfo = undefined;
|
||||
rconParser.Configuration.CommandPrefixes.RConResponse = '\xff\xff\xff\xff';
|
||||
rconParser.Configuration.CommandPrefixes.Tell = 'tell {0} {1}';
|
||||
rconParser.Configuration.CommandPrefixes.Say = 'say {0}';
|
||||
rconParser.Configuration.CommandPrefixes.Kick = 'dropclient {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.Ban = 'dropclient {0} "{1}"';
|
||||
rconParser.Configuration.CommandPrefixes.TempBan = 'tempbanclient {0} "{1}"';
|
||||
rconParser.Configuration.Dvar.AddMapping(107, 1); // RCon DvarValue
|
||||
rconParser.Configuration.Dvar.Pattern = '^(.*)$';
|
||||
rconParser.Version = 'IW5 MP 1.4 build 382 latest Thu Jan 19 2012 11:09:49AM win-x86';
|
||||
rconParser.GameName = 3; // IW5
|
||||
rconParser.CanGenerateLogPath = false;
|
||||
|
||||
eventParser.Configuration.GameDirectory = 'scripts';
|
||||
eventParser.Version = 'IW5 MP 1.4 build 382 latest Thu Jan 19 2012 11:09:49AM win-x86';
|
||||
eventParser.GameName = 3; // IW5
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
29
Plugins/ScriptPlugins/SharedGUIDKick.js
Normal file
29
Plugins/ScriptPlugins/SharedGUIDKick.js
Normal file
@ -0,0 +1,29 @@
|
||||
var plugin = {
|
||||
author: 'RaidMax',
|
||||
version: 1.1,
|
||||
name: 'Shared GUID Kicker Plugin',
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
// make sure we only check for IW4(x)
|
||||
if (server.GameName !== 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// connect or join event
|
||||
if (gameEvent.Type === 3) {
|
||||
// this GUID seems to have been packed in a IW4 torrent and results in an unreasonable amount of people using the same GUID
|
||||
if (gameEvent.Origin.NetworkId === -805366929435212061) {
|
||||
gameEvent.Origin.Kick('Your GUID is generic. Delete players/guids.dat and rejoin', _IW4MAdminClient);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
62
Plugins/ScriptPlugins/VPNDetection.js
Normal file
62
Plugins/ScriptPlugins/VPNDetection.js
Normal file
@ -0,0 +1,62 @@
|
||||
var plugin = {
|
||||
author: 'RaidMax',
|
||||
version: 1.1,
|
||||
name: 'VPN Detection Plugin',
|
||||
|
||||
manager: null,
|
||||
logger: null,
|
||||
vpnExceptionIds: [],
|
||||
|
||||
checkForVpn: function (origin) {
|
||||
var exempt = false;
|
||||
// prevent players that are exempt from being kicked
|
||||
this.vpnExceptionIds.forEach(function (id) {
|
||||
if (id === origin.ClientId) {
|
||||
exempt = true;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
if (exempt) {
|
||||
return;
|
||||
}
|
||||
|
||||
var usingVPN = false;
|
||||
|
||||
try {
|
||||
var cl = new System.Net.Http.HttpClient();
|
||||
var re = cl.GetAsync('https://api.xdefcon.com/proxy/check/?ip=' + origin.IPAddressString).Result;
|
||||
var co = re.Content;
|
||||
var parsedJSON = JSON.parse(co.ReadAsStringAsync().Result);
|
||||
co.Dispose();
|
||||
re.Dispose();
|
||||
cl.Dispose();
|
||||
usingVPN = parsedJSON.success && parsedJSON.proxy;
|
||||
} catch (e) {
|
||||
this.logger.WriteWarning('There was a problem checking client IP for VPN ' + e.message);
|
||||
}
|
||||
|
||||
if (usingVPN) {
|
||||
this.logger.WriteInfo(origin + ' is using a VPN (' + origin.IPAddressString + ')');
|
||||
origin.Kick(_localization.LocalizationIndex["SERVER_KICK_VPNS_NOTALLOWED"], _IW4MAdminClient);
|
||||
}
|
||||
},
|
||||
|
||||
onEventAsync: function (gameEvent, server) {
|
||||
// connect event
|
||||
if (gameEvent.Type === 3) {
|
||||
this.checkForVpn(gameEvent.Origin);
|
||||
}
|
||||
},
|
||||
|
||||
onLoadAsync: function (manager) {
|
||||
this.manager = manager;
|
||||
this.logger = manager.GetLogger(0);
|
||||
},
|
||||
|
||||
onUnloadAsync: function () {
|
||||
},
|
||||
|
||||
onTickAsync: function (server) {
|
||||
}
|
||||
};
|
@ -1,8 +1,7 @@
|
||||
using SharedLibraryCore.Helpers;
|
||||
using IW4MAdmin.Plugins.Stats.Models;
|
||||
using SharedLibraryCore.Helpers;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using SharedLibraryCore.Objects;
|
||||
using IW4MAdmin.Plugins.Stats.Helpers;
|
||||
using IW4MAdmin.Plugins.Stats.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@ -12,89 +11,187 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
{
|
||||
class Detection
|
||||
{
|
||||
public enum DetectionType
|
||||
{
|
||||
Bone,
|
||||
Chest,
|
||||
Offset,
|
||||
Strain
|
||||
};
|
||||
|
||||
public ChangeTracking<EFACSnapshot> Tracker { get; private set; }
|
||||
public const int QUEUE_COUNT = 10;
|
||||
|
||||
public List<EFClientKill> QueuedHits { get; set; }
|
||||
int Kills;
|
||||
int AboveThresholdCount;
|
||||
double AverageKillTime;
|
||||
int HitCount;
|
||||
Dictionary<IW4Info.HitLocation, int> HitLocationCount;
|
||||
double AngleDifferenceAverage;
|
||||
EFClientStatistics ClientStats;
|
||||
DateTime LastKill;
|
||||
long LastOffset;
|
||||
IW4Info.WeaponName LastWeapon;
|
||||
ILogger Log;
|
||||
Strain Strain;
|
||||
readonly DateTime ConnectionTime = DateTime.UtcNow;
|
||||
|
||||
public Detection(ILogger log, EFClientStatistics clientStats)
|
||||
{
|
||||
Log = log;
|
||||
HitLocationCount = new Dictionary<IW4Info.HitLocation, int>();
|
||||
foreach (var loc in Enum.GetValues(typeof(IW4Info.HitLocation)))
|
||||
{
|
||||
HitLocationCount.Add((IW4Info.HitLocation)loc, 0);
|
||||
LastKill = DateTime.UtcNow;
|
||||
}
|
||||
|
||||
ClientStats = clientStats;
|
||||
Strain = new Strain();
|
||||
Tracker = new ChangeTracking<EFACSnapshot>();
|
||||
QueuedHits = new List<EFClientKill>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Analyze kill and see if performed by a cheater
|
||||
/// </summary>
|
||||
/// <param name="kill">kill performed by the player</param>
|
||||
/// <param name="hit">kill performed by the player</param>
|
||||
/// <returns>true if detection reached thresholds, false otherwise</returns>
|
||||
public DetectionPenaltyResult ProcessKill(EFClientKill kill)
|
||||
public DetectionPenaltyResult ProcessHit(EFClientKill hit, bool isDamage)
|
||||
{
|
||||
if ((kill.DeathType != IW4Info.MeansOfDeath.MOD_PISTOL_BULLET &&
|
||||
kill.DeathType != IW4Info.MeansOfDeath.MOD_RIFLE_BULLET &&
|
||||
kill.DeathType != IW4Info.MeansOfDeath.MOD_HEAD_SHOT) ||
|
||||
kill.HitLoc == IW4Info.HitLocation.none)
|
||||
if ((hit.DeathType != IW4Info.MeansOfDeath.MOD_PISTOL_BULLET &&
|
||||
hit.DeathType != IW4Info.MeansOfDeath.MOD_RIFLE_BULLET &&
|
||||
hit.DeathType != IW4Info.MeansOfDeath.MOD_HEAD_SHOT) ||
|
||||
hit.HitLoc == IW4Info.HitLocation.none || hit.TimeOffset - LastOffset < 0 ||
|
||||
// hack: prevents false positives
|
||||
(LastWeapon != hit.Weapon && (hit.TimeOffset - LastOffset) == 50))
|
||||
{
|
||||
return new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Any,
|
||||
RatioAmount = 0
|
||||
};
|
||||
|
||||
HitLocationCount[kill.HitLoc]++;
|
||||
Kills++;
|
||||
AverageKillTime = (AverageKillTime + (DateTime.UtcNow - LastKill).TotalSeconds) / Kills;
|
||||
|
||||
#region VIEWANGLES
|
||||
double distance = Vector3.Distance(kill.KillOrigin, kill.DeathOrigin);
|
||||
double x = kill.KillOrigin.X + distance * Math.Cos(kill.ViewAngles.X.ToRadians()) * Math.Cos(kill.ViewAngles.Y.ToRadians());
|
||||
double y = kill.KillOrigin.Y + (distance * Math.Sin(kill.ViewAngles.X.ToRadians()) * Math.Cos(kill.ViewAngles.Y.ToRadians()));
|
||||
double z = kill.KillOrigin.Z + distance * Math.Sin((360.0f - kill.ViewAngles.Y).ToRadians());
|
||||
var trueVector = Vector3.Subtract(kill.KillOrigin, kill.DeathOrigin);
|
||||
var calculatedVector = Vector3.Subtract(kill.KillOrigin, new Vector3((float)x, (float)y, (float)z));
|
||||
double angle = trueVector.AngleBetween(calculatedVector);
|
||||
|
||||
if (kill.AdsPercent > 0.5 && kill.Distance > 3)
|
||||
{
|
||||
var hitLoc = ClientStats.HitLocations
|
||||
.First(hl => hl.Location == kill.HitLoc);
|
||||
float previousAverage = hitLoc.HitOffsetAverage;
|
||||
double newAverage = (previousAverage * (hitLoc.HitCount - 1) + angle) / hitLoc.HitCount;
|
||||
hitLoc.HitOffsetAverage = (float)newAverage;
|
||||
|
||||
if (double.IsNaN(hitLoc.HitOffsetAverage))
|
||||
{
|
||||
Log.WriteWarning("[Detection::ProcessKill] HitOffsetAvgerage NaN");
|
||||
Log.WriteDebug($"{previousAverage}-{hitLoc.HitCount}-{hitLoc}-{newAverage}");
|
||||
hitLoc.HitOffsetAverage = 0f;
|
||||
}
|
||||
}
|
||||
|
||||
DetectionPenaltyResult result = null;
|
||||
LastWeapon = hit.Weapon;
|
||||
|
||||
HitLocationCount[hit.HitLoc]++;
|
||||
HitCount++;
|
||||
|
||||
if (!isDamage)
|
||||
{
|
||||
Kills++;
|
||||
}
|
||||
|
||||
#region VIEWANGLES
|
||||
if (hit.AnglesList.Count >= 2)
|
||||
{
|
||||
double realAgainstPredict = Vector3.ViewAngleDistance(hit.AnglesList[0], hit.AnglesList[1], hit.ViewAngles);
|
||||
|
||||
// LIFETIME
|
||||
var hitLoc = ClientStats.HitLocations
|
||||
.First(hl => hl.Location == hit.HitLoc);
|
||||
|
||||
float previousAverage = hitLoc.HitOffsetAverage;
|
||||
double newAverage = (previousAverage * (hitLoc.HitCount - 1) + realAgainstPredict) / hitLoc.HitCount;
|
||||
hitLoc.HitOffsetAverage = (float)newAverage;
|
||||
|
||||
if (hitLoc.HitOffsetAverage > Thresholds.MaxOffset(hitLoc.HitCount) &&
|
||||
hitLoc.HitCount > 100)
|
||||
{
|
||||
//Log.WriteDebug("*** Reached Max Lifetime Average for Angle Difference ***");
|
||||
//Log.WriteDebug($"Lifetime Average = {newAverage}");
|
||||
//Log.WriteDebug($"Bone = {hitLoc.Location}");
|
||||
//Log.WriteDebug($"HitCount = {hitLoc.HitCount}");
|
||||
//Log.WriteDebug($"ID = {hit.AttackerId}");
|
||||
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
Value = hitLoc.HitOffsetAverage,
|
||||
HitCount = hitLoc.HitCount,
|
||||
Type = DetectionType.Offset
|
||||
};
|
||||
}
|
||||
|
||||
// SESSION
|
||||
double sessAverage = (AngleDifferenceAverage * (HitCount - 1) + realAgainstPredict) / HitCount;
|
||||
AngleDifferenceAverage = sessAverage;
|
||||
|
||||
if (sessAverage > Thresholds.MaxOffset(HitCount) &&
|
||||
HitCount > 30)
|
||||
{
|
||||
//Log.WriteDebug("*** Reached Max Session Average for Angle Difference ***");
|
||||
//Log.WriteDebug($"Session Average = {sessAverage}");
|
||||
//Log.WriteDebug($"HitCount = {HitCount}");
|
||||
//Log.WriteDebug($"ID = {hit.AttackerId}");
|
||||
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
Value = sessAverage,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Offset,
|
||||
Location = hitLoc.Location
|
||||
};
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
Log.WriteDebug($"PredictVsReal={realAgainstPredict}");
|
||||
#endif
|
||||
}
|
||||
|
||||
double currentStrain = Strain.GetStrain(isDamage, hit.Damage, hit.Distance / 0.0254, hit.ViewAngles, Math.Max(50, hit.TimeOffset - LastOffset));
|
||||
#if DEBUG == true
|
||||
Log.WriteDebug($"Current Strain: {currentStrain}");
|
||||
#endif
|
||||
LastOffset = hit.TimeOffset;
|
||||
|
||||
if (currentStrain > ClientStats.MaxStrain)
|
||||
{
|
||||
ClientStats.MaxStrain = currentStrain;
|
||||
}
|
||||
|
||||
// flag
|
||||
if (currentStrain > Thresholds.MaxStrainFlag)
|
||||
{
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Flag,
|
||||
Value = currentStrain,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Strain
|
||||
};
|
||||
}
|
||||
|
||||
// ban
|
||||
if (currentStrain > Thresholds.MaxStrainBan &&
|
||||
HitCount >= 5)
|
||||
{
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
Value = currentStrain,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Strain
|
||||
};
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region SESSION_RATIOS
|
||||
if (Kills >= Thresholds.LowSampleMinKills)
|
||||
{
|
||||
double marginOfError = Thresholds.GetMarginOfError(Kills);
|
||||
double marginOfError = Thresholds.GetMarginOfError(HitCount);
|
||||
// determine what the max headshot percentage can be for current number of kills
|
||||
double lerpAmount = Math.Min(1.0, (Kills - Thresholds.LowSampleMinKills) / (double)(Thresholds.HighSampleMinKills - Thresholds.LowSampleMinKills));
|
||||
double lerpAmount = Math.Min(1.0, (HitCount - Thresholds.LowSampleMinKills) / (double)(/*Thresholds.HighSampleMinKills*/ 60 - Thresholds.LowSampleMinKills));
|
||||
double maxHeadshotLerpValueForFlag = Thresholds.Lerp(Thresholds.HeadshotRatioThresholdLowSample(2.0), Thresholds.HeadshotRatioThresholdHighSample(2.0), lerpAmount) + marginOfError;
|
||||
double maxHeadshotLerpValueForBan = Thresholds.Lerp(Thresholds.HeadshotRatioThresholdLowSample(3.0), Thresholds.HeadshotRatioThresholdHighSample(3.0), lerpAmount) + marginOfError;
|
||||
double maxHeadshotLerpValueForBan = Thresholds.Lerp(Thresholds.HeadshotRatioThresholdLowSample(3.5), Thresholds.HeadshotRatioThresholdHighSample(3.5), lerpAmount) + marginOfError;
|
||||
// determine what the max bone percentage can be for current number of kills
|
||||
double maxBoneRatioLerpValueForFlag = Thresholds.Lerp(Thresholds.BoneRatioThresholdLowSample(2.25), Thresholds.BoneRatioThresholdHighSample(2.25), lerpAmount) + marginOfError;
|
||||
double maxBoneRatioLerpValueForBan = Thresholds.Lerp(Thresholds.BoneRatioThresholdLowSample(3.25), Thresholds.BoneRatioThresholdHighSample(3.25), lerpAmount) + marginOfError;
|
||||
|
||||
// calculate headshot ratio
|
||||
double currentHeadshotRatio = ((HitLocationCount[IW4Info.HitLocation.head] + HitLocationCount[IW4Info.HitLocation.helmet]) / (double)Kills);
|
||||
double currentHeadshotRatio = ((HitLocationCount[IW4Info.HitLocation.head] + HitLocationCount[IW4Info.HitLocation.helmet] + HitLocationCount[IW4Info.HitLocation.neck]) / (double)HitCount);
|
||||
|
||||
// calculate maximum bone
|
||||
double currentMaxBoneRatio = (HitLocationCount.Values.Select(v => v / (double)Kills).Max());
|
||||
double currentMaxBoneRatio = (HitLocationCount.Values.Select(v => v / (double)HitCount).Max());
|
||||
var bone = HitLocationCount.FirstOrDefault(b => b.Value == HitLocationCount.Values.Max()).Key;
|
||||
|
||||
#region HEADSHOT_RATIO
|
||||
@ -102,48 +199,52 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
if (currentHeadshotRatio > maxHeadshotLerpValueForFlag)
|
||||
{
|
||||
// ban on headshot
|
||||
if (currentHeadshotRatio > maxHeadshotLerpValueForFlag)
|
||||
if (currentHeadshotRatio > maxHeadshotLerpValueForBan)
|
||||
{
|
||||
AboveThresholdCount++;
|
||||
Log.WriteDebug("**Maximum Headshot Ratio Reached For Ban**");
|
||||
Log.WriteDebug($"ClientId: {kill.AttackerId}");
|
||||
Log.WriteDebug($"**Kills: {Kills}");
|
||||
Log.WriteDebug($"ClientId: {hit.AttackerId}");
|
||||
Log.WriteDebug($"**HitCount: {HitCount}");
|
||||
Log.WriteDebug($"**Ratio {currentHeadshotRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {maxHeadshotLerpValueForFlag}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in HitLocationCount)
|
||||
{
|
||||
sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
Log.WriteDebug(sb.ToString());
|
||||
Log.WriteDebug($"ThresholdReached: {AboveThresholdCount}");
|
||||
}
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
Log.WriteDebug(sb.ToString());
|
||||
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
RatioAmount = currentHeadshotRatio,
|
||||
Bone = IW4Info.HitLocation.head,
|
||||
KillCount = Kills
|
||||
Value = currentHeadshotRatio,
|
||||
Location = IW4Info.HitLocation.head,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Bone
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
AboveThresholdCount++;
|
||||
Log.WriteDebug("**Maximum Headshot Ratio Reached For Flag**");
|
||||
Log.WriteDebug($"ClientId: {kill.AttackerId}");
|
||||
Log.WriteDebug($"**Kills: {Kills}");
|
||||
Log.WriteDebug($"ClientId: {hit.AttackerId}");
|
||||
Log.WriteDebug($"**HitCount: {HitCount}");
|
||||
Log.WriteDebug($"**Ratio {currentHeadshotRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {maxHeadshotLerpValueForFlag}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in HitLocationCount)
|
||||
{
|
||||
sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
Log.WriteDebug(sb.ToString());
|
||||
Log.WriteDebug($"ThresholdReached: {AboveThresholdCount}");
|
||||
}
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
Log.WriteDebug(sb.ToString());
|
||||
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Flag,
|
||||
RatioAmount = currentHeadshotRatio,
|
||||
Bone = IW4Info.HitLocation.head,
|
||||
KillCount = Kills
|
||||
Value = currentHeadshotRatio,
|
||||
Location = IW4Info.HitLocation.head,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Bone
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -157,41 +258,49 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
if (currentMaxBoneRatio > maxBoneRatioLerpValueForBan)
|
||||
{
|
||||
Log.WriteDebug("**Maximum Bone Ratio Reached For Ban**");
|
||||
Log.WriteDebug($"ClientId: {kill.AttackerId}");
|
||||
Log.WriteDebug($"**Kills: {Kills}");
|
||||
Log.WriteDebug($"ClientId: {hit.AttackerId}");
|
||||
Log.WriteDebug($"**HitCount: {HitCount}");
|
||||
Log.WriteDebug($"**Ratio {currentMaxBoneRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {maxBoneRatioLerpValueForBan}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in HitLocationCount)
|
||||
{
|
||||
sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
}
|
||||
|
||||
Log.WriteDebug(sb.ToString());
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
RatioAmount = currentMaxBoneRatio,
|
||||
Bone = bone,
|
||||
KillCount = Kills
|
||||
Value = currentMaxBoneRatio,
|
||||
Location = bone,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Bone
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.WriteDebug("**Maximum Bone Ratio Reached For Flag**");
|
||||
Log.WriteDebug($"ClientId: {kill.AttackerId}");
|
||||
Log.WriteDebug($"**Kills: {Kills}");
|
||||
Log.WriteDebug($"ClientId: {hit.AttackerId}");
|
||||
Log.WriteDebug($"**HitCount: {HitCount}");
|
||||
Log.WriteDebug($"**Ratio {currentMaxBoneRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {maxBoneRatioLerpValueForFlag}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in HitLocationCount)
|
||||
{
|
||||
sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
}
|
||||
|
||||
Log.WriteDebug(sb.ToString());
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Flag,
|
||||
RatioAmount = currentMaxBoneRatio,
|
||||
Bone = bone,
|
||||
KillCount = Kills
|
||||
Value = currentMaxBoneRatio,
|
||||
Location = bone,
|
||||
HitCount = HitCount,
|
||||
Type = DetectionType.Bone
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -199,12 +308,12 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
}
|
||||
|
||||
#region CHEST_ABDOMEN_RATIO_SESSION
|
||||
int chestKills = HitLocationCount[IW4Info.HitLocation.torso_upper];
|
||||
int chestHits = HitLocationCount[IW4Info.HitLocation.torso_upper];
|
||||
|
||||
if (chestKills >= Thresholds.MediumSampleMinKills)
|
||||
if (chestHits >= Thresholds.MediumSampleMinKills)
|
||||
{
|
||||
double marginOfError = Thresholds.GetMarginOfError(chestKills);
|
||||
double lerpAmount = Math.Min(1.0, (chestKills - Thresholds.MediumSampleMinKills) / (double)(Thresholds.HighSampleMinKills - Thresholds.LowSampleMinKills));
|
||||
double marginOfError = Thresholds.GetMarginOfError(chestHits);
|
||||
double lerpAmount = Math.Min(1.0, (chestHits - Thresholds.MediumSampleMinKills) / (double)(Thresholds.HighSampleMinKills - Thresholds.LowSampleMinKills));
|
||||
// determine max acceptable ratio of chest to abdomen kills
|
||||
double chestAbdomenRatioLerpValueForFlag = Thresholds.Lerp(Thresholds.ChestAbdomenRatioThresholdLowSample(3), Thresholds.ChestAbdomenRatioThresholdHighSample(3), lerpAmount) + marginOfError;
|
||||
double chestAbdomenLerpValueForBan = Thresholds.Lerp(Thresholds.ChestAbdomenRatioThresholdLowSample(4), Thresholds.ChestAbdomenRatioThresholdHighSample(4), lerpAmount) + marginOfError;
|
||||
@ -214,72 +323,101 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
if (currentChestAbdomenRatio > chestAbdomenRatioLerpValueForFlag)
|
||||
{
|
||||
|
||||
if (currentChestAbdomenRatio > chestAbdomenLerpValueForBan && chestKills >= Thresholds.MediumSampleMinKills + 30)
|
||||
if (currentChestAbdomenRatio > chestAbdomenLerpValueForBan && chestHits >= Thresholds.MediumSampleMinKills + 30)
|
||||
{
|
||||
Log.WriteDebug("**Maximum Chest/Abdomen Ratio Reached For Ban**");
|
||||
Log.WriteDebug($"ClientId: {kill.AttackerId}");
|
||||
Log.WriteDebug($"**Chest Kills: {chestKills}");
|
||||
Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {chestAbdomenLerpValueForBan}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in HitLocationCount)
|
||||
sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
Log.WriteDebug(sb.ToString());
|
||||
// Log.WriteDebug($"ThresholdReached: {AboveThresholdCount}");
|
||||
//Log.WriteDebug("**Maximum Chest/Abdomen Ratio Reached For Ban**");
|
||||
//Log.WriteDebug($"ClientId: {hit.AttackerId}");
|
||||
//Log.WriteDebug($"**Chest Hits: {chestHits}");
|
||||
//Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
//Log.WriteDebug($"**MaxRatio {chestAbdomenLerpValueForBan}");
|
||||
//var sb = new StringBuilder();
|
||||
//foreach (var kvp in HitLocationCount)
|
||||
// sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
//Log.WriteDebug(sb.ToString());
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
RatioAmount = currentChestAbdomenRatio,
|
||||
Bone = 0,
|
||||
KillCount = chestKills
|
||||
Value = currentChestAbdomenRatio,
|
||||
Location = IW4Info.HitLocation.torso_upper,
|
||||
Type = DetectionType.Chest,
|
||||
HitCount = chestHits
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.WriteDebug("**Maximum Chest/Abdomen Ratio Reached For Flag**");
|
||||
Log.WriteDebug($"ClientId: {kill.AttackerId}");
|
||||
Log.WriteDebug($"**Chest Kills: {chestKills}");
|
||||
Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {chestAbdomenRatioLerpValueForFlag}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var kvp in HitLocationCount)
|
||||
sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
Log.WriteDebug(sb.ToString());
|
||||
// Log.WriteDebug($"ThresholdReached: {AboveThresholdCount}");
|
||||
//Log.WriteDebug("**Maximum Chest/Abdomen Ratio Reached For Flag**");
|
||||
//Log.WriteDebug($"ClientId: {hit.AttackerId}");
|
||||
//Log.WriteDebug($"**Chest Hits: {chestHits}");
|
||||
//Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
//Log.WriteDebug($"**MaxRatio {chestAbdomenRatioLerpValueForFlag}");
|
||||
//var sb = new StringBuilder();
|
||||
//foreach (var kvp in HitLocationCount)
|
||||
// sb.Append($"HitLocation: {kvp.Key} -> {kvp.Value}\r\n");
|
||||
//Log.WriteDebug(sb.ToString());
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
result = new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Flag,
|
||||
RatioAmount = currentChestAbdomenRatio,
|
||||
Bone = 0,
|
||||
KillCount = chestKills
|
||||
Value = currentChestAbdomenRatio,
|
||||
Location = IW4Info.HitLocation.torso_upper,
|
||||
Type = DetectionType.Chest,
|
||||
HitCount = chestHits
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
#endregion
|
||||
return new DetectionPenaltyResult()
|
||||
|
||||
Tracker.OnChange(new EFACSnapshot()
|
||||
{
|
||||
When = hit.When,
|
||||
ClientId = ClientStats.ClientId,
|
||||
SessionAngleOffset = AngleDifferenceAverage,
|
||||
CurrentSessionLength = (int)(DateTime.UtcNow - ConnectionTime).TotalSeconds,
|
||||
CurrentStrain = currentStrain,
|
||||
CurrentViewAngle = hit.ViewAngles,
|
||||
Hits = HitCount,
|
||||
Kills = Kills,
|
||||
Deaths = ClientStats.SessionDeaths,
|
||||
HitDestinationId = hit.DeathOrigin.Vector3Id,
|
||||
HitDestination = hit.DeathOrigin,
|
||||
HitOriginId = hit.KillOrigin.Vector3Id,
|
||||
HitOrigin = hit.KillOrigin,
|
||||
EloRating = ClientStats.EloRating,
|
||||
HitLocation = hit.HitLoc,
|
||||
LastStrainAngle = Strain.LastAngle,
|
||||
PredictedViewAngles = hit.AnglesList,
|
||||
// this is in "meters"
|
||||
Distance = hit.Distance,
|
||||
SessionScore = ClientStats.SessionScore,
|
||||
HitType = hit.DeathType,
|
||||
SessionSPM = ClientStats.SessionSPM,
|
||||
StrainAngleBetween = Strain.LastDistance,
|
||||
TimeSinceLastEvent = (int)Strain.LastDeltaTime,
|
||||
WeaponId = hit.Weapon
|
||||
});
|
||||
|
||||
return result ?? new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Any,
|
||||
RatioAmount = 0
|
||||
};
|
||||
}
|
||||
|
||||
public DetectionPenaltyResult ProcessTotalRatio(EFClientStatistics stats)
|
||||
{
|
||||
int totalChestKills = stats.HitLocations.Single(c => c.Location == IW4Info.HitLocation.torso_upper).HitCount;
|
||||
int totalChestHits = stats.HitLocations.Single(c => c.Location == IW4Info.HitLocation.torso_upper).HitCount;
|
||||
|
||||
if (totalChestKills >= 60)
|
||||
if (totalChestHits >= 60)
|
||||
{
|
||||
double marginOfError = Thresholds.GetMarginOfError(totalChestKills);
|
||||
double lerpAmount = Math.Min(1.0, (totalChestKills - 60) / 250.0);
|
||||
double marginOfError = Thresholds.GetMarginOfError(totalChestHits);
|
||||
double lerpAmount = Math.Min(1.0, (totalChestHits - 60) / 250.0);
|
||||
// determine max acceptable ratio of chest to abdomen kills
|
||||
double chestAbdomenRatioLerpValueForFlag = Thresholds.Lerp(Thresholds.ChestAbdomenRatioThresholdHighSample(3.0), Thresholds.ChestAbdomenRatioThresholdHighSample(2), lerpAmount) + marginOfError;
|
||||
double chestAbdomenLerpValueForBan = Thresholds.Lerp(Thresholds.ChestAbdomenRatioThresholdHighSample(4.0), Thresholds.ChestAbdomenRatioThresholdHighSample(4.0), lerpAmount) + marginOfError;
|
||||
double chestAbdomenRatioLerpValueForFlag = Thresholds.Lerp(Thresholds.ChestAbdomenRatioThresholdHighSample(3.0), Thresholds.ChestAbdomenRatioThresholdHighSample(2.0), lerpAmount) + marginOfError;
|
||||
double chestAbdomenLerpValueForBan = Thresholds.Lerp(Thresholds.ChestAbdomenRatioThresholdHighSample(4.0), Thresholds.ChestAbdomenRatioThresholdHighSample(3.0), lerpAmount) + marginOfError;
|
||||
|
||||
double currentChestAbdomenRatio = totalChestKills /
|
||||
double currentChestAbdomenRatio = totalChestHits /
|
||||
stats.HitLocations.Single(hl => hl.Location == IW4Info.HitLocation.torso_lower).HitCount;
|
||||
|
||||
if (currentChestAbdomenRatio > chestAbdomenRatioLerpValueForFlag)
|
||||
@ -287,44 +425,44 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
|
||||
if (currentChestAbdomenRatio > chestAbdomenLerpValueForBan)
|
||||
{
|
||||
Log.WriteDebug("**Maximum Lifetime Chest/Abdomen Ratio Reached For Ban**");
|
||||
Log.WriteDebug($"ClientId: {stats.ClientId}");
|
||||
Log.WriteDebug($"**Total Chest Kills: {totalChestKills}");
|
||||
Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {chestAbdomenLerpValueForBan}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var location in stats.HitLocations)
|
||||
sb.Append($"HitLocation: {location.Location} -> {location.HitCount}\r\n");
|
||||
Log.WriteDebug(sb.ToString());
|
||||
// Log.WriteDebug($"ThresholdReached: {AboveThresholdCount}");
|
||||
//Log.WriteDebug("**Maximum Lifetime Chest/Abdomen Ratio Reached For Ban**");
|
||||
//Log.WriteDebug($"ClientId: {stats.ClientId}");
|
||||
//Log.WriteDebug($"**Total Chest Hits: {totalChestHits}");
|
||||
//Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
//Log.WriteDebug($"**MaxRatio {chestAbdomenLerpValueForBan}");
|
||||
//var sb = new StringBuilder();
|
||||
//foreach (var location in stats.HitLocations)
|
||||
// sb.Append($"HitLocation: {location.Location} -> {location.HitCount}\r\n");
|
||||
//Log.WriteDebug(sb.ToString());
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Ban,
|
||||
RatioAmount = currentChestAbdomenRatio,
|
||||
Bone = IW4Info.HitLocation.torso_upper,
|
||||
KillCount = totalChestKills
|
||||
Value = currentChestAbdomenRatio,
|
||||
Location = IW4Info.HitLocation.torso_upper,
|
||||
HitCount = totalChestHits,
|
||||
Type = DetectionType.Chest
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.WriteDebug("**Maximum Lifetime Chest/Abdomen Ratio Reached For Flag**");
|
||||
Log.WriteDebug($"ClientId: {stats.ClientId}");
|
||||
Log.WriteDebug($"**Total Chest Kills: {totalChestKills}");
|
||||
Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
Log.WriteDebug($"**MaxRatio {chestAbdomenRatioLerpValueForFlag}");
|
||||
var sb = new StringBuilder();
|
||||
foreach (var location in stats.HitLocations)
|
||||
sb.Append($"HitLocation: {location.Location} -> {location.HitCount}\r\n");
|
||||
Log.WriteDebug(sb.ToString());
|
||||
// Log.WriteDebug($"ThresholdReached: {AboveThresholdCount}");
|
||||
//Log.WriteDebug("**Maximum Lifetime Chest/Abdomen Ratio Reached For Flag**");
|
||||
//Log.WriteDebug($"ClientId: {stats.ClientId}");
|
||||
//Log.WriteDebug($"**Total Chest Hits: {totalChestHits}");
|
||||
//Log.WriteDebug($"**Ratio {currentChestAbdomenRatio}");
|
||||
//Log.WriteDebug($"**MaxRatio {chestAbdomenRatioLerpValueForFlag}");
|
||||
//var sb = new StringBuilder();
|
||||
//foreach (var location in stats.HitLocations)
|
||||
// sb.Append($"HitLocation: {location.Location} -> {location.HitCount}\r\n");
|
||||
//Log.WriteDebug(sb.ToString());
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
{
|
||||
ClientPenalty = Penalty.PenaltyType.Flag,
|
||||
RatioAmount = currentChestAbdomenRatio,
|
||||
Bone = IW4Info.HitLocation.torso_upper,
|
||||
KillCount = totalChestKills
|
||||
Value = currentChestAbdomenRatio,
|
||||
Location = IW4Info.HitLocation.torso_upper,
|
||||
HitCount = totalChestHits,
|
||||
Type = DetectionType.Chest
|
||||
};
|
||||
}
|
||||
}
|
||||
@ -332,7 +470,6 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
|
||||
return new DetectionPenaltyResult()
|
||||
{
|
||||
Bone = IW4Info.HitLocation.none,
|
||||
ClientPenalty = Penalty.PenaltyType.Any
|
||||
};
|
||||
}
|
||||
|
@ -1,17 +1,13 @@
|
||||
using SharedLibraryCore.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
{
|
||||
class DetectionPenaltyResult
|
||||
{
|
||||
public Detection.DetectionType Type { get; set; }
|
||||
public Penalty.PenaltyType ClientPenalty { get; set; }
|
||||
public double RatioAmount { get; set; }
|
||||
public IW4Info.HitLocation Bone { get; set; }
|
||||
public int KillCount { get; set; }
|
||||
public double Value { get; set; }
|
||||
public IW4Info.HitLocation Location { get; set; }
|
||||
public int HitCount { get; set; }
|
||||
}
|
||||
}
|
||||
|
54
Plugins/Stats/Cheat/Strain.cs
Normal file
54
Plugins/Stats/Cheat/Strain.cs
Normal file
@ -0,0 +1,54 @@
|
||||
using SharedLibraryCore.Helpers;
|
||||
using SharedLibraryCore.Interfaces;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
{
|
||||
class Strain
|
||||
{
|
||||
private const double StrainDecayBase = 0.9;
|
||||
private double CurrentStrain;
|
||||
public double LastDistance { get; private set; }
|
||||
public Vector3 LastAngle { get; private set; }
|
||||
public double LastDeltaTime { get; private set; }
|
||||
|
||||
public double GetStrain(bool isDamage, int damage, double killDistance, Vector3 newAngle, double deltaTime)
|
||||
{
|
||||
if (LastAngle == null)
|
||||
LastAngle = newAngle;
|
||||
|
||||
LastDeltaTime = deltaTime;
|
||||
|
||||
double decayFactor = GetDecay(deltaTime);
|
||||
CurrentStrain *= decayFactor;
|
||||
double[] distance = Helpers.Extensions.AngleStuff(newAngle, LastAngle);
|
||||
LastDistance = distance[0] + distance[1];
|
||||
|
||||
#if DEBUG == true
|
||||
Console.WriteLine($"Angle Between = {LastDistance}");
|
||||
Console.WriteLine($"Distance From Target = {killDistance}");
|
||||
Console.WriteLine($"Time Offset = {deltaTime}");
|
||||
Console.WriteLine($"Decay Factor = {decayFactor} ");
|
||||
#endif
|
||||
// this happens on first kill
|
||||
if ((distance[0] == 0 && distance[1] == 0) ||
|
||||
deltaTime == 0 ||
|
||||
double.IsNaN(CurrentStrain))
|
||||
{
|
||||
return CurrentStrain;
|
||||
}
|
||||
|
||||
double newStrain = Math.Pow(LastDistance, 0.99) / deltaTime;
|
||||
newStrain *= killDistance / 1000.0;
|
||||
|
||||
CurrentStrain += newStrain;
|
||||
|
||||
LastAngle = newAngle;
|
||||
return CurrentStrain;
|
||||
}
|
||||
|
||||
private double GetDecay(double deltaTime) => Math.Pow(StrainDecayBase, Math.Pow(2.0, deltaTime / 250.0) / 1000.0);
|
||||
}
|
||||
}
|
@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
{
|
||||
@ -31,6 +27,11 @@ namespace IW4MAdmin.Plugins.Stats.Cheat
|
||||
public const int HighSampleMinKills = 100;
|
||||
public const double KillTimeThreshold = 0.2;
|
||||
|
||||
public const double MaxStrainBan = 0.9;
|
||||
|
||||
public static double MaxOffset(int sampleSize) => Math.Exp(Math.Max(-3.07 + (-3.07 / Math.Sqrt(sampleSize)), -3.07 - (-3.07 / Math.Sqrt(sampleSize))) + 4 * (0.869));
|
||||
public const double MaxStrainFlag = 0.36;
|
||||
|
||||
public static double GetMarginOfError(int numKills) => 1.6455 / Math.Sqrt(numKills);
|
||||
|
||||
public static double Lerp(double v1, double v2, double amount)
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user