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

Cleaned up some code and adhered closer to the Microsoft code standards.

This commit is contained in:
RaidMax
2017-06-12 13:50:00 -04:00
parent 7a81f6c2bd
commit 0ef306a60c
22 changed files with 507 additions and 573 deletions

View File

@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Text;
using System.Linq;
using SharedLibrary;
using SharedLibrary.Network;
using System.Threading.Tasks;
@ -12,22 +11,22 @@ namespace SharedLibrary.Commands
{
public CQuit(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)
public override Task ExecuteAsync(Event E)
{
E.Owner.Manager.Stop();
return Task.Run(() => { E.Owner.Manager.Stop(); });
}
}
class Owner : Command
class COwner : Command
{
public Owner(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
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)
{
if (E.Owner.Manager.GetClientDatabase().GetOwner() == null)
{
E.Origin.setLevel(Player.Permission.Owner);
E.Origin.SetLevel(Player.Permission.Owner);
await E.Origin.Tell("Congratulations, you have claimed ownership of this server!");
E.Owner.owner = E.Origin;
E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Origin);
@ -74,7 +73,7 @@ namespace SharedLibrary.Commands
if (E.Origin.Level > E.Target.Level)
await E.Target.Kick(E.Target.lastOffense, E.Origin);
else
await E.Origin.Tell("You cannot kick " + E.Target.Name);
await E.Origin.Tell($"You cannot kick {E.Target.Name}");
}
}
@ -84,7 +83,7 @@ namespace SharedLibrary.Commands
public override async Task ExecuteAsync(Event E)
{
await E.Owner.Broadcast("^1" + E.Origin.Name + " - ^6" + E.Data + "^7");
await E.Owner.Broadcast($"^:{E.Origin.Name} - ^6{E.Data}^7");
}
}
@ -284,31 +283,15 @@ namespace SharedLibrary.Commands
if (newPerm == Player.Permission.Owner && E.Origin.Level != Player.Permission.Console)
newPerm = Player.Permission.Banned;
bool playerInOtherServer = false;
if (newPerm > Player.Permission.Banned)
{
E.Target.setLevel(newPerm);
// prevent saving of old permissions on disconnect
// todo: manager DB
foreach (var server in E.Owner.Manager.GetServers())
{
foreach (var player in server.GetPlayersAsList())
{
if (player != null && player.NetworkID == E.Target.NetworkID)
{
player.setLevel(newPerm);
await E.Target.Tell("Congratulations! You have been promoted to ^3" + newPerm);
playerInOtherServer = true;
}
}
}
var ActiveClient = E.Owner.Manager.GetActiveClients().First(p => p.NetworkID == E.Target.NetworkID);
ActiveClient?.SetLevel(newPerm);
if (!playerInOtherServer)
await E.Target.Tell("Congratulations! You have been promoted to ^3" + newPerm);
await E.Origin.Tell(E.Target.Name + " was successfully promoted!");
//NEEED TO MOVE
await ActiveClient?.Tell("Congratulations! You have been promoted to ^3" + newPerm);
await E.Origin.Tell($"{E.Target.Name} was successfully promoted!");
E.Target.SetLevel(newPerm);
E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Target);
}
@ -398,7 +381,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.levelToColor(P.Level), P.IP, P.GetLastConnection());
await E.Origin.Tell(mesg);
}
}
@ -516,14 +499,14 @@ namespace SharedLibrary.Commands
if (E.Target.Level == Player.Permission.Flagged)
{
E.Target.setLevel(Player.Permission.User);
E.Target.SetLevel(Player.Permission.User);
await E.Origin.Tell("You have ^5unflagged ^7" + E.Target.Name);
}
else
{
E.Data = Utilities.RemoveWords(E.Data, 1);
E.Target.setLevel(Player.Permission.Flagged);
E.Target.SetLevel(Player.Permission.Flagged);
E.Owner.Manager.GetClientPenalties().AddPenalty(new Penalty(Penalty.Type.Flag, E.Data, E.Target.NetworkID, E.Origin.NetworkID, DateTime.Now, E.Target.IP));
await E.Origin.Tell("You have ^5flagged ^7" + E.Target.Name);
}

View File

@ -16,12 +16,6 @@ namespace SharedLibrary
}
public String timeString()
{
return Time.ToShortTimeString();
}
//public Player Origin { get; private set; }
public String Message { get; private set; }
public DateTime Time { get; private set; }
public string Name;
@ -30,7 +24,7 @@ namespace SharedLibrary
[Serializable]
public struct RestEvent
{
public RestEvent(eType Ty, eVersion V, string M, string T, string O, string Ta)
public RestEvent(EventType Ty, EventVersion V, string M, string T, string O, string Ta)
{
Type = Ty;
Version = V;
@ -42,20 +36,20 @@ namespace SharedLibrary
ID = Math.Abs(DateTime.Now.GetHashCode());
}
public enum eType
public enum EventType
{
NOTIFICATION,
STATUS,
ALERT,
}
public enum eVersion
public enum EventVersion
{
IW4MAdmin
}
public eType Type;
public eVersion Version;
public EventType Type;
public EventVersion Version;
public string Message;
public string Title;
public string Origin;

View File

@ -10,86 +10,30 @@ namespace SharedLibrary
{
public IFile(String fileName)
{
//Not safe for directories with more than one folder but meh
string[] asd = fileName.Split('/');
if (asd[0] != "")
_Directory = asd[0];
else
_Directory = asd[2];
Name = (fileName.Split('/'))[fileName.Split('/').Length - 1];
try
{
Handle = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
sze = Handle.BaseStream.Length;
}
catch
{
//Console.WriteLine("Unable to open log file for writing!");
}
}
public IFile(String file, bool write)
{
Name = file;
writeHandle = new StreamWriter(new FileStream(Name, FileMode.Create, FileAccess.Write, FileShare.ReadWrite));
sze = 0;
}
public IFile()
{
WebClient request = new WebClient();
string url = $"http://raidmax.org/logs/IW4X/games_mp.log";
byte[] newFileData = request.DownloadData(url);
Handle = new StreamReader(new MemoryStream(newFileData));
Name = fileName;
Handle = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
sze = Handle.BaseStream.Length;
}
public long getSize()
public long Length()
{
sze = Handle.BaseStream.Length;
return sze;
}
public void Write(String line)
{
if (writeHandle != null)
{
try
{
writeHandle.WriteLine(line);
writeHandle.Flush();
}
catch (Exception E)
{
Console.WriteLine("Error during flush", E.Message);
}
}
}
public void Close()
{
if (Handle != null)
Handle.Close();
if (writeHandle != null)
writeHandle.Close();
Handle?.Close();
}
public String[] readAll()
public String[] ReadAllLines()
{
return Handle.ReadToEnd().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
return Handle?.ReadToEnd().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
}
public String getLines()
public String GetText()
{
return Handle.ReadToEnd();
return Handle?.ReadToEnd();
}
public String[] Tail(int lineCount)
@ -122,8 +66,6 @@ namespace SharedLibrary
private long sze;
private String Name;
private String _Directory;
private StreamReader Handle;
private StreamWriter writeHandle;
}
}

View File

@ -14,5 +14,6 @@ namespace SharedLibrary.Interfaces
ClientsDB GetClientDatabase();
AliasesDB GetAliasesDatabase();
IList<MessageToken> GetMessageTokens();
IList<Player> GetActiveClients();
}
}

View File

@ -122,23 +122,23 @@ namespace SharedLibrary
return $"{Name}::{NetworkID}";
}
public String getLastConnection()
public String GetLastConnection()
{
return Utilities.timePassed(LastConnection);
}
public void updateName(String n)
public void UpdateName(String n)
{
if (n.Trim() != String.Empty)
Name = n;
}
public void updateIP(String I)
public void SetIP(String I)
{
IP = I;
}
public void setLevel(Permission Perm)
public void SetLevel(Permission Perm)
{
Level = Perm;
}
@ -184,6 +184,5 @@ namespace SharedLibrary
public int Warnings;
public Aliases Alias;
public bool Masked;
public int selectedServer;
}
}

View File

@ -25,7 +25,7 @@ namespace SharedLibrary.Network
var ServerOOBConnection = new UdpClient();
ServerOOBConnection.Client.SendTimeout = 1000;
ServerOOBConnection.Client.ReceiveTimeout = 1000;
var Endpoint = new IPEndPoint(IPAddress.Parse(QueryServer.getIP()), QueryServer.getPort());
var Endpoint = new IPEndPoint(IPAddress.Parse(QueryServer.GetIP()), QueryServer.GetPort());
string QueryString = String.Empty;

View File

@ -26,21 +26,21 @@ namespace SharedLibrary
Players = new List<Player>(new Player[18]);
events = new Queue<Event>();
Reports = new List<Report>();
playerHistory = new Queue<PlayerHistory>();
PlayerHistory = new Queue<PlayerHistory>();
ChatHistory = new List<Chat>();
lastWebChat = DateTime.Now;
nextMessage = 0;
initMacros();
initMessages();
initMaps();
initRules();
InitializeTokens();
InitializeAutoMessages();
InitializeMaps();
InitializeRules();
var commands = mgr.GetCommands();
owner = Manager.GetClientDatabase().GetOwner();
if (owner == null)
commands.Add(new Owner("owner", "claim ownership of the server", "owner", Player.Permission.User, 0, false));
commands.Add(new COwner("owner", "claim ownership of the server", "owner", Player.Permission.User, 0, false));
commands.Add(new CQuit("quit", "quit IW4MAdmin", "q", Player.Permission.Owner, 0, false));
commands.Add(new CKick("kick", "kick a player by name. syntax: !kick <player> <reason>.", "k", Player.Permission.Trusted, 2, true));
@ -73,25 +73,14 @@ namespace SharedLibrary
commands.Add(new CFindAllPlayers("findall", "find a player by their aliase(s). syntax: !findall <player>", "fa", Player.Permission.Moderator, 1, false));
}
//Returns the current server name -- *STRING*
public String getName()
{
return Hostname;
}
public String getGametype()
{
return Gametype;
}
//Returns current server IP set by `net_ip` -- *STRING*
public String getIP()
public String GetIP()
{
return IP;
}
//Returns current server port set by `net_port` -- *INT*
public int getPort()
public int GetPort()
{
return Port;
}
@ -109,7 +98,7 @@ namespace SharedLibrary
/// <param name="Origin">Player to scan for aliases</param>
abstract public List<Aliases> GetAliases(Player Origin);
public List<Player> getPlayerAliases(Player Origin)
public List<Player> GetPlayerAliases(Player Origin)
{
List<int> databaseIDs = new List<int>();
@ -284,36 +273,20 @@ namespace SharedLibrary
await this.ExecuteCommandAsync($"map {newMap.Name}");
}
public void webChat(Player P, String Message)
{
DateTime requestTime = DateTime.Now;
if ((requestTime - lastWebChat).TotalSeconds > 1)
{
Broadcast("^1[WEBCHAT] ^5" + P.Name + "^7 - " + Message);
if (Message.Length > 50)
Message = Message.Substring(0, 50) + "...";
ChatHistory.Add(new Chat(P.Name, Utilities.StripColors(Message), DateTime.Now));
lastWebChat = DateTime.Now;
}
}
/// <summary>
/// Initalize the macro variables
/// </summary>
abstract public void initMacros();
abstract public void InitializeTokens();
/// <summary>
/// Read the map configuration
/// </summary>
protected void initMaps()
protected void InitializeMaps()
{
maps = new List<Map>();
IFile mapfile = new IFile("config/maps.cfg");
String[] _maps = mapfile.readAll();
String[] _maps = mapfile.ReadAllLines();
mapfile.Close();
if (_maps.Length > 2) // readAll returns minimum one empty string
{
@ -333,13 +306,14 @@ namespace SharedLibrary
/// <summary>
/// Initialize the messages to be broadcasted
/// todo: this needs to be a serialized file
/// </summary>
protected void initMessages()
protected void InitializeAutoMessages()
{
messages = new List<String>();
IFile messageCFG = new IFile("config/messages.cfg");
String[] lines = messageCFG.readAll();
String[] lines = messageCFG.ReadAllLines();
messageCFG.Close();
if (lines.Length < 2) //readAll returns minimum one empty string
@ -370,13 +344,14 @@ namespace SharedLibrary
/// <summary>
/// Initialize the rules configuration
/// todo: this needs to be a serialized file
/// </summary>
protected void initRules()
protected void InitializeRules()
{
rules = new List<String>();
IFile ruleFile = new IFile("config/rules.cfg");
String[] _rules = ruleFile.readAll();
String[] _rules = ruleFile.ReadAllLines();
ruleFile.Close();
if (_rules.Length > 2) // readAll returns minimum one empty string
{
@ -400,7 +375,7 @@ namespace SharedLibrary
/// <summary>
/// Load up the built in commands
/// </summary>
abstract public void initCommands();
abstract public void InitializeCommands();
//Objects
public Interfaces.IManager Manager { get; protected set; }
@ -414,7 +389,7 @@ namespace SharedLibrary
public int totalKills = 0;
public List<Report> Reports;
public List<Chat> ChatHistory;
public Queue<PlayerHistory> playerHistory { get; private set; }
public Queue<PlayerHistory> PlayerHistory { get; private set; }
protected int ConnectionErrors;
protected DateTime LastPoll;

View File

@ -7,11 +7,11 @@ namespace SharedLibrary
{
public class WebService
{
public static List<IPage> pageList { get; private set; }
public static List<IPage> PageList { get; private set; }
public static void Init()
{
pageList = new List<IPage>();
PageList = new List<IPage>();
}
}
@ -24,10 +24,10 @@ namespace SharedLibrary
public interface IPage
{
string getPath();
string getName();
HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers);
bool isVisible();
string GetPath();
string GetName();
HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers);
bool Visible();
}
public abstract class HTMLPage : IPage
@ -44,57 +44,57 @@ namespace SharedLibrary
this.visible = visible;
}
protected string getContentType()
protected string GetContentType()
{
return "text/html";
}
protected string loadFile(string filename)
protected string LoadFile(string filename)
{
string s;
IFile HTML = new IFile(filename);
s = HTML.getLines();
s = HTML.GetText();
HTML.Close();
return s;
}
protected string loadHeader()
protected string LoadHeader()
{
return loadFile("webfront\\header.html");
return LoadFile("webfront\\header.html");
}
protected string loadFooter()
protected string LoadFooter()
{
return loadFile("webfront\\footer.html");
return LoadFile("webfront\\footer.html");
}
public bool isVisible()
public bool Visible()
{
return visible;
}
virtual public string getPath()
virtual public string GetPath()
{
return "";
}
abstract public string getName();
virtual public Dictionary<string, string> getHeaders(IDictionary<string, string> requestHeaders)
abstract public string GetName();
virtual public Dictionary<string, string> GetHeaders(IDictionary<string, string> requestHeaders)
{
return new Dictionary<string, string>();
}
abstract public string getContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers);
abstract public string GetContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers);
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{
HttpResponse resp = new HttpResponse()
{
content = getContent(querySet, headers),
contentType = getContentType(),
additionalHeaders = getHeaders(headers)
content = GetContent(querySet, headers),
contentType = GetContentType(),
additionalHeaders = GetHeaders(headers)
};
return resp;
}