1
0
mirror of https://github.com/RaidMax/IW4M-Admin.git synced 2025-06-10 15:20:48 -05:00

More cleanup

project renaming
moved PluginImporter to SharedLibrary
config writer abstracted for plugins
This commit is contained in:
RaidMax
2017-06-12 17:47:31 -04:00
parent 0ef306a60c
commit 5d1c9bd218
36 changed files with 303 additions and 330 deletions

View File

@ -18,8 +18,7 @@ namespace SharedLibrary.Commands
}
class COwner : Command
{
{
public COwner(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
@ -145,7 +144,7 @@ namespace SharedLibrary.Commands
public override async Task ExecuteAsync(Event E)
{
String You = String.Format("{0} [^3#{1}^7] {2} [^3@{3}^7] [{4}^7] IP: {5}", E.Origin.Name, E.Origin.ClientID, E.Origin.NetworkID, E.Origin.DatabaseID, SharedLibrary.Utilities.levelToColor(E.Origin.Level), E.Origin.IP);
String You = String.Format("{0} [^3#{1}^7] {2} [^3@{3}^7] [{4}^7] IP: {5}", E.Origin.Name, E.Origin.ClientID, E.Origin.NetworkID, E.Origin.DatabaseID, SharedLibrary.Utilities.ConvertLevelToColor(E.Origin.Level), E.Origin.IP);
await E.Origin.Tell(You);
}
}
@ -166,9 +165,9 @@ namespace SharedLibrary.Commands
continue;
if (P.Masked)
playerList.AppendFormat("[^3{0}^7]{3}[^3{1}^7] {2}", Utilities.levelToColor(Player.Permission.User), P.ClientID, P.Name, SharedLibrary.Utilities.getSpaces(Player.Permission.SeniorAdmin.ToString().Length - Player.Permission.User.ToString().Length));
playerList.AppendFormat("[^3{0}^7]{3}[^3{1}^7] {2}", Utilities.ConvertLevelToColor(Player.Permission.User), P.ClientID, P.Name, SharedLibrary.Utilities.GetSpaces(Player.Permission.SeniorAdmin.ToString().Length - Player.Permission.User.ToString().Length));
else
playerList.AppendFormat("[^3{0}^7]{3}[^3{1}^7] {2}", Utilities.levelToColor(P.Level), P.ClientID, P.Name, SharedLibrary.Utilities.getSpaces(Player.Permission.SeniorAdmin.ToString().Length - P.Level.ToString().Length));
playerList.AppendFormat("[^3{0}^7]{3}[^3{1}^7] {2}", Utilities.ConvertLevelToColor(P.Level), P.ClientID, P.Name, SharedLibrary.Utilities.GetSpaces(Player.Permission.SeniorAdmin.ToString().Length - P.Level.ToString().Length));
if (count == 2 || E.Owner.GetPlayersAsList().Count == 1)
{
@ -278,7 +277,7 @@ namespace SharedLibrary.Commands
return;
}
Player.Permission newPerm = Utilities.matchPermission(Utilities.RemoveWords(E.Data, 1));
Player.Permission newPerm = Utilities.MatchPermission(Utilities.RemoveWords(E.Data, 1));
if (newPerm == Player.Permission.Owner && E.Origin.Level != Player.Permission.Console)
newPerm = Player.Permission.Banned;
@ -333,9 +332,9 @@ namespace SharedLibrary.Commands
if (P != null && P.Level > Player.Permission.Flagged && !P.Masked)
{
if (E.Message[0] == '@')
await E.Owner.Broadcast(String.Format("[^3{0}^7] {1}", Utilities.levelToColor(P.Level), P.Name));
await E.Owner.Broadcast(String.Format("[^3{0}^7] {1}", Utilities.ConvertLevelToColor(P.Level), P.Name));
else
await E.Origin.Tell(String.Format("[^3{0}^7] {1}", Utilities.levelToColor(P.Level), P.Name));
await E.Origin.Tell(String.Format("[^3{0}^7] {1}", Utilities.ConvertLevelToColor(P.Level), P.Name));
}
}
}
@ -381,7 +380,7 @@ namespace SharedLibrary.Commands
foreach (Player P in db_players)
{
String mesg = String.Format("[^3{0}^7] [^3@{1}^7] - [{2}^7] - {3} | last seen {4} ago", P.Name, P.DatabaseID, SharedLibrary.Utilities.levelToColor(P.Level), P.IP, P.GetLastConnection());
String mesg = String.Format("[^3{0}^7] [^3@{1}^7] - [{2}^7] - {3} | last seen {4} ago", P.Name, P.DatabaseID, SharedLibrary.Utilities.ConvertLevelToColor(P.Level), P.IP, P.GetLastConnection());
await E.Origin.Tell(mesg);
}
}
@ -679,5 +678,19 @@ namespace SharedLibrary.Commands
await E.Origin.Tell("Successfully sent RCON command!");
}
}
class CPlugins : Command
{
public CPlugins(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
{
await E.Origin.Tell("^5Loaded Plugins:");
foreach (var P in Plugins.PluginImporter.ActivePlugins)
{
await E.Origin.Tell(String.Format("^3{0} ^7[v^3{1}^7] by ^5{2}^7", P.Name, P.Version, P.Author));
}
}
}
}

View File

@ -509,7 +509,7 @@ namespace SharedLibrary
{
Dictionary<String, object> newPlayer = new Dictionary<String, object>
{
{ "Name", Utilities.removeNastyChars(P.Name) },
{ "Name", Utilities.StripIllegalCharacters(P.Name) },
{ "npID", P.NetworkID },
{ "Level", (int)P.Level },
{ "LastOffense", "" },
@ -546,7 +546,7 @@ namespace SharedLibrary
{
Dictionary<String, object> newBan = new Dictionary<String, object>
{
{ "Reason", Utilities.removeNastyChars(B.Reason) },
{ "Reason", Utilities.StripIllegalCharacters(B.Reason) },
{ "npID", B.OffenderID },
{ "bannedByID", B.PenaltyOriginID },
{ "IP", B.IP },
@ -656,7 +656,7 @@ namespace SharedLibrary
Dictionary<String, object> newPlayer = new Dictionary<String, object>
{
{ "Number", Alias.Number },
{ "NAMES", Utilities.removeNastyChars(String.Join(";", Alias.Names)) },
{ "NAMES", Utilities.StripIllegalCharacters(String.Join(";", Alias.Names)) },
{ "IPS", String.Join(";", Alias.IPS) }
};
Insert("ALIASES", newPlayer);

View File

@ -119,7 +119,7 @@ namespace SharedLibrary
{
Regex rgx = new Regex("[^a-zA-Z0-9 -! -_]");
string message = rgx.Replace(line[4], "");
return new Event(GType.Say, Utilities.removeNastyChars(message).StripColors(), SV.ParseClientFromString(line, 2), null, SV) { Message = Utilities.removeNastyChars(message).StripColors() };
return new Event(GType.Say, Utilities.StripIllegalCharacters(message).StripColors(), SV.ParseClientFromString(line, 2), null, SV) { Message = Utilities.StripIllegalCharacters(message).StripColors() };
}
if (eventType == ":")

View File

@ -5,7 +5,7 @@ using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SharedLibrary
namespace SharedLibrary.Helpers
{
public sealed class AsyncStatus
{

View File

@ -0,0 +1,50 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibrary.Helpers
{
public class Configuration<T> : Interfaces.Serialize<T>
{
string FilePostfix;
public Configuration(Server S)
{
FilePostfix = $"_{S.GetIP()}_{S.GetPort()}.cfg";
}
public T Read()
{
try
{
return Read();
}
catch (Exceptions.SerializeException)
{
return default(T);
}
}
public bool Write(T Data)
{
try
{
Write(Filename(), Data);
return true;
}
catch(Exceptions.SerializeException)
{
return false;
}
}
public override string Filename()
{
return $"config/{typeof(T).ToString()}_{FilePostfix}";
}
}
}

View File

@ -1,6 +1,6 @@
using System;
namespace SharedLibrary
namespace SharedLibrary.Helpers
{
public class MessageToken
{

View File

@ -1,6 +1,6 @@
using System;
namespace SharedLibrary
namespace SharedLibrary.Helpers
{
public class PlayerHistory
{

View File

@ -13,7 +13,7 @@ namespace SharedLibrary.Interfaces
IPenaltyList GetClientPenalties();
ClientsDB GetClientDatabase();
AliasesDB GetAliasesDatabase();
IList<MessageToken> GetMessageTokens();
IList<Helpers.MessageToken> GetMessageTokens();
IList<Player> GetActiveClients();
}
}

View File

@ -5,8 +5,8 @@ namespace SharedLibrary.Interfaces
{
public interface IPlugin
{
Task OnLoadAsync();
Task OnUnloadAsync();
Task OnLoadAsync(Server S);
Task OnUnloadAsync(Server S);
Task OnEventAsync(Event E, Server S);
Task OnTickAsync(Server S);

View File

@ -1,4 +1,5 @@
using System;
using SharedLibrary;
namespace SharedLibrary
{
@ -6,7 +7,7 @@ namespace SharedLibrary
{
public Penalty(Type BType, String Reas, String TargID, String From, DateTime time, String ip)
{
Reason = Reas.Replace("!","");
Reason = Reas.CleanChars().StripColors();
OffenderID = TargID;
PenaltyOriginID = From;
When = time;
@ -36,4 +37,18 @@ namespace SharedLibrary
public String IP { get; private set; }
public Type BType { get; private set; }
}
public class Report
{
public Report(Player T, Player O, String R)
{
Target = T;
Origin = O;
Reason = R;
}
public Player Target { get; private set; }
public Player Origin { get; private set; }
public String Reason { get; private set; }
}
}

View File

@ -124,7 +124,7 @@ namespace SharedLibrary
public String GetLastConnection()
{
return Utilities.timePassed(LastConnection);
return Utilities.GetTimePassed(LastConnection);
}
public void UpdateName(String n)

View File

@ -0,0 +1,78 @@
using System;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using SharedLibrary.Interfaces;
namespace SharedLibrary.Plugins
{
public class PluginImporter
{
public static List<Command> ActiveCommands = new List<Command>();
public static List<IPlugin> ActivePlugins = new List<IPlugin>();
public static bool Load(IManager Manager)
{
string[] dllFileNames = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\plugins", "*.dll");
if (dllFileNames.Length == 0)
{
Manager.GetLogger().WriteDebug("No plugins found to load");
return true;
}
ICollection<Assembly> assemblies = new List<Assembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames)
{
byte[] rawDLL = File.ReadAllBytes(dllFile);
Assembly assembly = Assembly.Load(rawDLL);
assemblies.Add(assembly);
}
int LoadedPlugins = 0;
int LoadedCommands = 0;
foreach (Assembly Plugin in assemblies)
{
if (Plugin != null)
{
Type[] types = Plugin.GetTypes();
foreach (Type assemblyType in types)
{
if (assemblyType.IsClass && assemblyType.BaseType.Name == "Command")
{
Object commandObject = Activator.CreateInstance(assemblyType);
Command newCommand = (Command)commandObject;
ActiveCommands.Add(newCommand);
Manager.GetLogger().WriteDebug("Registered command \"" + newCommand.Name + "\"");
LoadedCommands++;
continue;
}
try
{
if (assemblyType.GetInterface("IPlugin", false) == null)
continue;
Object notifyObject = Activator.CreateInstance(assemblyType);
IPlugin newNotify = (IPlugin)notifyObject;
if (ActivePlugins.Find(x => x.Name == newNotify.Name) == null)
{
ActivePlugins.Add(newNotify);
Manager.GetLogger().WriteDebug($"Loaded plugin \"{ newNotify.Name }\" [{newNotify.Version}]");
LoadedPlugins++;
}
}
catch (Exception E)
{
Manager.GetLogger().WriteWarning($"Could not load plugin {Plugin.Location} - {E.Message}");
}
}
}
}
Manager.GetLogger().WriteInfo($"Loaded {LoadedPlugins} plugins and registered {LoadedCommands} commands.");
return true;
}
}
}

View File

@ -114,7 +114,7 @@ namespace SharedLibrary.Network
public static async Task SetDvarAsync(this Server server, string dvarName, object dvarValue)
{
await Task.FromResult(SendQuery(QueryType.DVAR, server, $"{dvarName} {dvarValue}"));
await Task.FromResult(SendQuery(QueryType.DVAR, server, $"set {dvarName} {dvarValue}"));
}
public static async Task<string[]> ExecuteCommandAsync(this Server server, string commandName)
@ -139,7 +139,6 @@ namespace SharedLibrary.Network
fixedRequest[i / 2] = initialRequestBytes[i];
return fixedRequest;
}
}
}

View File

@ -1,18 +0,0 @@
using System;
namespace SharedLibrary
{
public class Report
{
public Report(Player T, Player O, String R)
{
Target = T;
Origin = O;
Reason = R;
}
public Player Target { get; private set; }
public Player Origin { get; private set; }
public String Reason { get; private set; }
}
}

View File

@ -26,7 +26,7 @@ namespace SharedLibrary
Players = new List<Player>(new Player[18]);
events = new Queue<Event>();
Reports = new List<Report>();
PlayerHistory = new Queue<PlayerHistory>();
PlayerHistory = new Queue<SharedLibrary.Helpers.PlayerHistory>();
ChatHistory = new List<Chat>();
lastWebChat = DateTime.Now;
nextMessage = 0;
@ -71,6 +71,7 @@ namespace SharedLibrary
commands.Add(new CListAlias("alias", "get past aliases and ips of a player. syntax: !alias <player>", "known", Player.Permission.Moderator, 1, true));
commands.Add(new CExecuteRCON("rcon", "send rcon command to server. syntax: !rcon <command>", "rcon", Player.Permission.Owner, 1, false));
commands.Add(new CFindAllPlayers("findall", "find a player by their aliase(s). syntax: !findall <player>", "fa", Player.Permission.Moderator, 1, false));
commands.Add(new CPlugins("plugins", "view all loaded plugins. syntax: !plugins", "p", Player.Permission.Administrator, 0, false));
}
//Returns current server IP set by `net_ip` -- *STRING*
@ -375,7 +376,11 @@ namespace SharedLibrary
/// <summary>
/// Load up the built in commands
/// </summary>
abstract public void InitializeCommands();
public void InitializeCommands()
{
foreach (Command C in Plugins.PluginImporter.ActiveCommands)
Manager.GetCommands().Add(C);
}
//Objects
public Interfaces.IManager Manager { get; protected set; }
@ -389,7 +394,7 @@ namespace SharedLibrary
public int totalKills = 0;
public List<Report> Reports;
public List<Chat> ChatHistory;
public Queue<PlayerHistory> PlayerHistory { get; private set; }
public Queue<Helpers.PlayerHistory> PlayerHistory { get; private set; }
protected int ConnectionErrors;
protected DateTime LastPoll;

View File

@ -66,18 +66,19 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AsyncStatus.cs" />
<Compile Include="Helpers\AsyncStatus.cs" />
<Compile Include="Commands\NativeCommands.cs" />
<Compile Include="Exceptions\CommandException.cs" />
<Compile Include="Exceptions\DvarException.cs" />
<Compile Include="Exceptions\NetworkException.cs" />
<Compile Include="Exceptions\SerializationException.cs" />
<Compile Include="Exceptions\ServerException.cs" />
<Compile Include="Helpers\Configuration.cs" />
<Compile Include="Interfaces\ILogger.cs" />
<Compile Include="Interfaces\IManager.cs" />
<Compile Include="Interfaces\IPenaltyList.cs" />
<Compile Include="Interfaces\ISerializable.cs" />
<Compile Include="MessageToken.cs" />
<Compile Include="Helpers\MessageToken.cs" />
<Compile Include="Penalty.cs" />
<Compile Include="Command.cs" />
<Compile Include="Database.cs" />
@ -85,12 +86,12 @@
<Compile Include="File.cs" />
<Compile Include="Dvar.cs" />
<Compile Include="Map.cs" />
<Compile Include="Miscellaneous.cs" />
<Compile Include="Helpers\PlayerHistory.cs" />
<Compile Include="Player.cs" />
<Compile Include="Interfaces\IPlugin.cs" />
<Compile Include="PluginImporter.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RCON.cs" />
<Compile Include="Report.cs" />
<Compile Include="Server.cs" />
<Compile Include="Utilities.cs" />
<Compile Include="WebService.cs" />

View File

@ -10,7 +10,7 @@ namespace SharedLibrary
public static class Utilities
{
//Get string with specified number of spaces -- really only for visual output
public static String getSpaces(int Num)
public static String GetSpaces(int Num)
{
String SpaceString = String.Empty;
while (Num > 0)
@ -22,12 +22,6 @@ namespace SharedLibrary
return SpaceString;
}
//Sleep for x amount of seconds
public static void Wait(double time)
{
Thread.Sleep((int)Math.Ceiling(time * 1000));
}
//Remove words from a space delimited string
public static String RemoveWords(this string str, int num)
{
@ -74,14 +68,11 @@ namespace SharedLibrary
return StatusPlayers;
}
public static Player.Permission matchPermission(String str)
public static Player.Permission MatchPermission(String str)
{
String lookingFor = str.ToLower();
#if REPZ_BUILD
for (Player.Permission Perm = Player.Permission.User; Perm <= Player.Permission.Owner; Perm++)
#else
for (Player.Permission Perm = Player.Permission.User; Perm < Player.Permission.Owner; Perm++)
#endif
{
if (lookingFor.Contains(Perm.ToString().ToLower()))
return Perm;
@ -90,12 +81,10 @@ namespace SharedLibrary
return Player.Permission.Banned;
}
public static String removeNastyChars(String str)
public static String StripIllegalCharacters(String str)
{
if (str != null)
{
return str.Replace("`", "").Replace("\\", "").Replace("\"", "").Replace("&quot;", "").Replace("&amp;", "&").Replace("\"", "''").Replace("'", "").Replace("?", "");
}
else
return String.Empty;
@ -130,7 +119,7 @@ namespace SharedLibrary
/// </summary>
/// <param name="level">Specified player level</param>
/// <returns></returns>
public static String levelToColor(Player.Permission level)
public static String ConvertLevelToColor(Player.Permission level)
{
switch (level)
{
@ -149,7 +138,7 @@ namespace SharedLibrary
}
}
public static String ProcessMessageToken(IList<MessageToken> tokens, String str)
public static String ProcessMessageToken(IList<Helpers.MessageToken> tokens, String str)
{
MatchCollection RegexMatches = Regex.Matches(str, @"\{\{[A-Z]+\}\}", RegexOptions.IgnoreCase);
foreach (Match M in RegexMatches)
@ -176,7 +165,7 @@ namespace SharedLibrary
/// </summary>
/// <param name="input">Shorthand gametype reported from server</param>
/// <returns></returns>
public static String gametypeLocalized(String input)
public static String GetLocalizedGametype(String input)
{
switch (input)
{
@ -232,7 +221,7 @@ namespace SharedLibrary
return datetime.ToString("yyyy-MM-dd H:mm:ss");
}
public static String timePassed(DateTime start)
public static String GetTimePassed(DateTime start)
{
TimeSpan Elapsed = DateTime.Now - start;
@ -259,52 +248,5 @@ namespace SharedLibrary
else
return "a very long time";
}
public static String TimesConnected(this Player P)
{
int connection = P.Connections;
String Prefix = String.Empty;
if (connection % 10 > 3 || connection % 10 == 0 || (connection % 100 > 9 && connection % 100 < 19))
Prefix = "th";
else
{
switch (connection % 10)
{
case 1:
Prefix = "st";
break;
case 2:
Prefix = "nd";
break;
case 3:
Prefix = "rd";
break;
}
}
switch (connection)
{
case 0:
case 1:
return "first";
case 2:
return "second";
case 3:
return "third";
case 4:
return "fourth";
case 5:
return "fifth";
case 100:
return "One-Hundreth (amazing!)";
case 500:
return "you're really ^5dedicated ^7to this server! This is your ^5500th^7";
case 1000:
return "you deserve a medal. it's your ^11000th^7";
default:
return connection.ToString() + Prefix;
}
}
}
}