1
0
mirror of https://github.com/RaidMax/IW4M-Admin.git synced 2025-07-06 03:50:18 -05:00

support UTF8 in log files

sayteam registered as say event
updated readme
This commit is contained in:
RaidMax
2018-04-19 17:52:48 -05:00
parent 8e9d8e46c7
commit 75439e8c2a
11 changed files with 190 additions and 612 deletions

View File

@ -1,20 +1,11 @@
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using SharedLibrary;
using SharedLibrary.Interfaces;
using SharedLibrary.Helpers;
using SharedLibrary.Objects;
using System.Text.RegularExpressions;
using StatsPlugin.Models;
using SharedLibrary.Services;
using SharedLibrary.Database.Models;
using SharedLibrary.Database;
using SharedLibraryCore;
using SharedLibraryCore.Interfaces;
using SharedLibraryCore.Helpers;
namespace IW4MAdmin.Plugins
{
@ -26,12 +17,9 @@ namespace IW4MAdmin.Plugins
public string Author => "RaidMax";
private DateTime Interval;
public async Task OnEventAsync(Event E, Server S)
public async Task OnEventAsync(GameEvent E, Server S)
{
return;
if (E.Type == Event.GType.Start)
if (E.Type == GameEvent.EventType.Start)
{
#region PLAYER_HISTORY
var rand = new Random(GetHashCode());
@ -61,361 +49,11 @@ namespace IW4MAdmin.Plugins
}
}
public async Task OnLoadAsync(IManager manager)
{
// #if DO_IMPORT
var svc = new GenericRepository<EFServer>();
svc.Insert(new EFServer()
{
Active = true,
Port = 28960,
ServerId = Math.Abs("127.0.0.1:28960".GetHashCode()),
});
svc.Insert(new EFServer()
{
Active = true,
Port = 28965,
ServerId = Math.Abs("127.0.0.1:28965".GetHashCode()),
});
svc.Insert(new EFServer()
{
Active = true,
Port = 28970,
ServerId = Math.Abs("127.0.0.1:28970".GetHashCode()),
});
svc.SaveChanges();
// #endif
Interval = DateTime.Now;
var clients = new List<Player>();
var oldClients = new Dictionary<int, Player>();
#region CLIENTS
if (File.Exists("import_clients.csv"))
{
manager.GetLogger().WriteVerbose("Beginning import of existing clients");
var lines = File.ReadAllLines("import_clients.csv").Skip(1);
foreach (string line in lines)
{
string[] fields = Regex.Replace(line, "\".*\"", "").Split(',');
fields.All(f =>
{
f = f.StripColors().Trim();
return true;
});
if (fields.Length != 11)
{
manager.GetLogger().WriteError("Invalid client import file... aborting import");
return;
}
if (fields[1].Substring(0, 5) == "01100" || fields[0] == string.Empty || fields[1] == string.Empty || fields[6] == string.Empty)
continue;
if (!Regex.Match(fields[6], @"^\d+\.\d+\.\d+.\d+$").Success)
fields[6] = "0";
var client = new Player()
{
Name = fields[0],
NetworkId = fields[1].ConvertLong(),
IPAddress = fields[6].ConvertToIP(),
Level = (Player.Permission)Convert.ToInt32(fields[3]),
Connections = Convert.ToInt32(fields[5]),
LastConnection = DateTime.Parse(fields[7]),
};
clients.Add(client);
oldClients.Add(Convert.ToInt32(fields[2]), client);
}
clients = clients.Distinct().ToList();
// #if DO_IMPORT
/*clients = clients
.GroupBy(c => new { c.Name, c.IPAddress })
.Select(c => c.FirstOrDefault())
.ToList();*/
//newClients = clients.ToList();
//newClients.ForEach(c => c.ClientId = 0);
manager.GetLogger().WriteVerbose($"Read {clients.Count} clients for import");
try
{
SharedLibrary.Database.Importer.ImportClients(clients);
}
catch (Exception e)
{
manager.GetLogger().WriteError("Saving imported clients failed");
}
// #endif
}
#endregion
// load the entire database lol
var ctx = new DatabaseContext();
ctx.Configuration.ProxyCreationEnabled = false;
var cls = ctx.Clients.Include("AliasLink.Children").ToList(); //manager.GetClientService().Find(c => c.Active).Result;
ctx.Dispose();
#region ALIASES
if (File.Exists("import_aliases.csv"))
{
manager.GetLogger().WriteVerbose("Beginning import of existing aliases");
var aliases = new List<EFAlias>();
var lines = File.ReadAllLines("import_aliases.csv").Skip(1);
foreach (string line in lines)
{
string[] fields = Regex.Replace(line, "\".*\"", "").Split(',');
fields.All(f =>
{
f = f.StripColors().Trim();
return true;
});
if (fields.Length != 3)
{
manager.GetLogger().WriteError("Invalid alias import file... aborting import");
return;
}
try
{
int number = Int32.Parse(fields[0]);
var names = fields[1].Split(';').Where(n => n != String.Empty && n.Length > 2);
var oldClient = oldClients[number];
var newClient = cls.FirstOrDefault(c => c.NetworkId == oldClient.NetworkId);
foreach (string name in names)
{
// this is slow :D
if (newClient.AliasLink.Children.FirstOrDefault(n => n.Name == name) != null) continue;
var alias = new EFAlias()
{
Active = true,
DateAdded = DateTime.UtcNow,
Name = name,
LinkId = newClient.AliasLinkId,
IPAddress = newClient.IPAddress
};
aliases.Add(alias);
}
}
catch (KeyNotFoundException)
{
continue;
}
catch (Exception)
{
manager.GetLogger().WriteVerbose($"Could not import alias with line {line}");
}
}
SharedLibrary.Database.Importer.ImportSQLite(aliases);
}
#endregion
#region PENALTIES
if (File.Exists("import_penalties.csv"))
{
var penalties = new List<Penalty>();
manager.GetLogger().WriteVerbose("Beginning import of existing penalties");
foreach (string line in File.ReadAllLines("import_penalties.csv").Skip(1))
{
string comma = Regex.Match(line, "\".*,.*\"").Value.Replace(",", "");
string[] fields = Regex.Replace(line, "\".*,.*\"", comma).Split(',');
fields.All(f =>
{
f = f.StripColors().Trim();
return true;
});
if (fields.Length != 7)
{
manager.GetLogger().WriteError("Invalid penalty import file... aborting import");
return;
}
if (fields[2].Substring(0, 5) == "01100" || fields[2].Contains("0000000"))
continue;
try
{
var expires = DateTime.Parse(fields[6]);
var when = DateTime.Parse(fields[5]);
var penaltyType = (Penalty.PenaltyType)Int32.Parse(fields[0]);
if (penaltyType == Penalty.PenaltyType.Ban)
expires = DateTime.MaxValue;
var penalty = new Penalty()
{
Type = penaltyType,
Expires = expires == DateTime.MinValue ? when : expires,
Punisher = new SharedLibrary.Database.Models.EFClient() { NetworkId = fields[3].ConvertLong() },
Offender = new SharedLibrary.Database.Models.EFClient() { NetworkId = fields[2].ConvertLong() },
Offense = fields[1].Replace("\"", "").Trim(),
Active = true,
When = when,
};
penalties.Add(penalty);
}
catch (Exception e)
{
manager.GetLogger().WriteVerbose($"Could not import penalty with line {line}");
}
}
//#if DO_IMPORT
SharedLibrary.Database.Importer.ImportPenalties(penalties);
manager.GetLogger().WriteVerbose($"Imported {penalties.Count} penalties");
//#endif
}
#endregion
#region CHATHISTORY
if (File.Exists("import_chathistory.csv"))
{
var chatHistory = new List<EFClientMessage>();
manager.GetLogger().WriteVerbose("Beginning import of existing messages");
foreach (string line in File.ReadAllLines("import_chathistory.csv").Skip(1))
{
string comma = Regex.Match(line, "\".*,.*\"").Value.Replace(",", "");
string[] fields = Regex.Replace(line, "\".*,.*\"", comma).Split(',');
fields.All(f =>
{
f = f.StripColors().Trim();
return true;
});
if (fields.Length != 4)
{
manager.GetLogger().WriteError("Invalid chat history import file... aborting import");
return;
}
try
{
int cId = Convert.ToInt32(fields[0]);
var linkedClient = oldClients[cId];
var newcl = cls.FirstOrDefault(c => c.NetworkId == linkedClient.NetworkId);
if (newcl == null)
newcl = cls.FirstOrDefault(c => c.Name == linkedClient.Name && c.IPAddress == linkedClient.IPAddress);
int newCId = newcl.ClientId;
var chatMessage = new EFClientMessage()
{
Active = true,
ClientId = newCId,
Message = fields[1],
TimeSent = DateTime.Parse(fields[3]),
ServerId = Math.Abs($"127.0.0.1:{Convert.ToInt32(fields[2]).ToString()}".GetHashCode())
};
chatHistory.Add(chatMessage);
}
catch (Exception e)
{
manager.GetLogger().WriteVerbose($"Could not import chatmessage with line {line}");
}
}
manager.GetLogger().WriteVerbose($"Read {chatHistory.Count} messages for import");
SharedLibrary.Database.Importer.ImportSQLite(chatHistory);
}
#endregion
#region STATS
foreach (string file in Directory.GetFiles(Environment.CurrentDirectory))
{
if (Regex.Match(file, @"import_stats_[0-9]+.csv").Success)
{
int port = Int32.Parse(Regex.Match(file, "[0-9]{5}").Value);
var stats = new List<EFClientStatistics>();
manager.GetLogger().WriteVerbose("Beginning import of existing client stats");
var lines = File.ReadAllLines(file).Skip(1);
foreach (string line in lines)
{
string[] fields = line.Split(',');
if (fields.Length != 9)
{
manager.GetLogger().WriteError("Invalid client import file... aborting import");
return;
}
try
{
if (fields[0].Substring(0, 5) == "01100")
continue;
long id = fields[0].ConvertLong();
var client = cls.Single(c => c.NetworkId == id);
var time = Convert.ToInt32(fields[8]);
double spm = time < 60 ? 0 : Math.Round(Convert.ToInt32(fields[1]) * 100.0 / time, 3);
if (spm > 1000)
spm = 0;
var st = new EFClientStatistics()
{
Active = true,
ClientId = client.ClientId,
ServerId = Math.Abs($"127.0.0.1:{port}".GetHashCode()),
Kills = Convert.ToInt32(fields[1]),
Deaths = Convert.ToInt32(fields[2]),
SPM = spm,
Skill = 0,
TimePlayed = time * 60
};
// client.TotalConnectionTime += time;
stats.Add(st);
stats = stats.AsEnumerable()
.GroupBy(c => new { c.ClientId })
.Select(c => c.FirstOrDefault()).ToList();
var cl = await manager.GetClientService().Get(st.ClientId);
cl.TotalConnectionTime += time * 60;
await manager.GetClientService().Update(cl);
}
catch (Exception e)
{
continue;
}
}
manager.GetLogger().WriteVerbose($"Read {stats.Count} clients stats for import");
try
{
SharedLibrary.Database.Importer.ImportSQLite(stats);
}
catch (Exception e)
{
manager.GetLogger().WriteError("Saving imported stats failed");
}
}
}
#endregion
}
public Task OnLoadAsync(IManager manager) => Task.CompletedTask;
public async Task OnTickAsync(Server S)
{
return;
/*
if ((DateTime.Now - Interval).TotalSeconds > 1)
{
var rand = new Random();
@ -492,13 +130,10 @@ namespace IW4MAdmin.Plugins
}
}
}
*/
}
public async Task OnUnloadAsync()
{
}
public Task OnUnloadAsync() => Task.CompletedTask;
}
}
#endif

View File

@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b8c2a759-8663-4f6f-9ba4-19595f5e12c1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -1,97 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{B8C2A759-8663-4F6F-9BA4-19595F5E12C1}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Tests</RootNamespace>
<AssemblyName>Tests</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFramework>netcoreapp2.0</TargetFramework>
<ApplicationIcon />
<StartupObject />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release-Nightly|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release-Nightly|x86' ">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-Stable|AnyCPU'">
<OutputPath>bin\Release-Stable\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-Stable|x86'">
<OutputPath>bin\x86\Release-Stable\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>TRACE;DEBUG;NETCOREAPP2_0</DefineConstants>
</PropertyGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy &quot;$(TargetPath)&quot; &quot;$(SolutionDir)BUILD\Plugins&quot;" />
</Target>
<ItemGroup>
<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<ProjectReference Include="..\..\SharedLibraryCore\SharedLibraryCore.csproj" />
</ItemGroup>
<ItemGroup>
<Compile Include="Plugin.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\SharedLibrary\SharedLibrary.csproj">
<Project>{d51eeceb-438a-47da-870f-7d7b41bc24d6}</Project>
<Name>SharedLibrary</Name>
</ProjectReference>
<ProjectReference Include="..\SimpleStats\StatsPlugin.csproj">
<Project>{4785ab75-66f3-4391-985d-63a5a049a0fa}</Project>
<Name>StatsPlugin</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>if $(ConfigurationName) == Debug (copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)BUILD\plugins\")</PostBuildEvent>
</PropertyGroup>
</Project>
</Project>