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

@ -123,7 +123,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Commands.cs" /> <Compile Include="Commands.cs" />
<Compile Include="Config.cs" /> <Compile Include="ServerConfig.cs" />
<Compile Include="Kayak.cs" /> <Compile Include="Kayak.cs" />
<Compile Include="Logger.cs" /> <Compile Include="Logger.cs" />
<Compile Include="Main.cs" /> <Compile Include="Main.cs" />

View File

@ -13,6 +13,11 @@ namespace IW4MAdmin
{ {
public void OnException(IScheduler scheduler, Exception e) public void OnException(IScheduler scheduler, Exception e)
{ {
// it looks like there's a library error in
// Kayak.Http.HttpServerTransactionDelegate.OnError
if (e.GetType() == typeof(NullReferenceException))
return;
Manager.GetInstance().Logger.WriteWarning("Web service has encountered an error - " + e.Message); Manager.GetInstance().Logger.WriteWarning("Web service has encountered an error - " + e.Message);
Manager.GetInstance().Logger.WriteDebug($"Stack Trace: {e.StackTrace}"); Manager.GetInstance().Logger.WriteDebug($"Stack Trace: {e.StackTrace}");
@ -26,7 +31,7 @@ namespace IW4MAdmin
public void OnStop(IScheduler scheduler) public void OnStop(IScheduler scheduler)
{ {
Manager.GetInstance().Logger.WriteDebug("Web service has been stopped..."); Manager.GetInstance().Logger.WriteInfo("Web service has been stopped...");
} }
} }

View File

@ -40,7 +40,7 @@ namespace IW4MAdmin
Console.WriteLine(LogLine); Console.WriteLine(LogLine);
File.AppendAllText(FileName, LogLine + Environment.NewLine); File.AppendAllText(FileName, LogLine + Environment.NewLine);
#else #else
//if (type == LogType.Error || type == LogType.Verbose) if (type == LogType.Error || type == LogType.Verbose)
Console.WriteLine(LogLine); Console.WriteLine(LogLine);
//if (type != LogType.Debug) //if (type != LogType.Debug)
File.AppendAllText(FileName, LogLine + Environment.NewLine); File.AppendAllText(FileName, LogLine + Environment.NewLine);

View File

@ -44,6 +44,7 @@ namespace IW4MAdmin
do do
{ {
userInput = Console.ReadLine(); userInput = Console.ReadLine();
if (userInput.ToLower() == "quit") if (userInput.ToLower() == "quit")
ServerManager.Stop(); ServerManager.Stop();
@ -55,7 +56,7 @@ namespace IW4MAdmin
ServerManager.Servers[0].ExecuteEvent(E); ServerManager.Servers[0].ExecuteEvent(E);
Console.Write('>'); Console.Write('>');
} while (userInput != null && ServerManager.Running); } while (ServerManager.Running);
}); });
} }

View File

@ -66,14 +66,14 @@ namespace IW4MAdmin
var Configs = Directory.EnumerateFiles("config/servers").Where(x => x.Contains(".cfg")); var Configs = Directory.EnumerateFiles("config/servers").Where(x => x.Contains(".cfg"));
if (Configs.Count() == 0) if (Configs.Count() == 0)
Config.Generate(); ServerConfig.Generate();
SharedLibrary.WebService.Init(); SharedLibrary.WebService.Init();
PluginImporter.Load(); PluginImporter.Load();
foreach (var file in Configs) foreach (var file in Configs)
{ {
var Conf = Config.Read(file); var Conf = ServerConfig.Read(file);
var ServerInstance = new IW4MServer(this, Conf.IP, Conf.Port, Conf.Password); var ServerInstance = new IW4MServer(this, Conf.IP, Conf.Port, Conf.Password);
Task.Run(async () => Task.Run(async () =>
@ -125,7 +125,7 @@ namespace IW4MAdmin
{ {
Status.Update(new Task(() => (Status.Dependant as Server).ProcessUpdatesAsync(Status.GetToken()))); Status.Update(new Task(() => (Status.Dependant as Server).ProcessUpdatesAsync(Status.GetToken())));
if (Status.RunAverage > 500) if (Status.RunAverage > 500)
Logger.WriteWarning($"Update task average execution is longer than desired for {(Status.Dependant as Server).getIP()}::{(Status.Dependant as Server).getPort()} [{Status.RunAverage}ms]"); Logger.WriteWarning($"Update task average execution is longer than desired for {(Status.Dependant as Server).GetIP()}::{(Status.Dependant as Server).GetPort()} [{Status.RunAverage}ms]");
} }
} }
@ -170,5 +170,15 @@ namespace IW4MAdmin
{ {
return MessageTokens; 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;
}
} }
} }

View File

@ -13,7 +13,7 @@ namespace IW4MAdmin
{ {
public IW4MServer(SharedLibrary.Interfaces.IManager mgr, string address, int port, string password) : base(mgr, address, port, password) public IW4MServer(SharedLibrary.Interfaces.IManager mgr, string address, int port, string password) : base(mgr, address, port, password)
{ {
initCommands(); InitializeCommands();
} }
private void GetAliases(List<Aliases> returnAliases, Aliases currentAlias) private void GetAliases(List<Aliases> returnAliases, Aliases currentAlias)
@ -85,7 +85,7 @@ namespace IW4MAdmin
} }
// below this needs to be optimized ~ 425ms runtime // below this needs to be optimized ~ 425ms runtime
NewPlayer.updateName(P.Name.Trim()); NewPlayer.UpdateName(P.Name.Trim());
NewPlayer.Alias = Manager.GetAliasesDatabase().GetPlayerAliases(NewPlayer.DatabaseID); NewPlayer.Alias = Manager.GetAliasesDatabase().GetPlayerAliases(NewPlayer.DatabaseID);
if (NewPlayer.Alias == null) if (NewPlayer.Alias == null)
@ -102,7 +102,7 @@ namespace IW4MAdmin
// lets check aliases // lets check aliases
if ((NewPlayer.Alias.Names.Find(m => m.Equals(P.Name))) == null || NewPlayer.Name == null || NewPlayer.Name == String.Empty) if ((NewPlayer.Alias.Names.Find(m => m.Equals(P.Name))) == null || NewPlayer.Name == null || NewPlayer.Name == String.Empty)
{ {
NewPlayer.updateName(P.Name.Trim()); NewPlayer.UpdateName(P.Name.Trim());
NewPlayer.Alias.Names.Add(NewPlayer.Name); NewPlayer.Alias.Names.Add(NewPlayer.Name);
} }
@ -112,7 +112,7 @@ namespace IW4MAdmin
NewPlayer.Alias.IPS.Add(P.IP); NewPlayer.Alias.IPS.Add(P.IP);
} }
NewPlayer.updateIP(P.IP); NewPlayer.SetIP(P.IP);
Manager.GetAliasesDatabase().UpdatePlayerAliases(NewPlayer.Alias); Manager.GetAliasesDatabase().UpdatePlayerAliases(NewPlayer.Alias);
Manager.GetClientDatabase().UpdatePlayer(NewPlayer); Manager.GetClientDatabase().UpdatePlayer(NewPlayer);
@ -127,7 +127,7 @@ namespace IW4MAdmin
return true; return true;
} }
List<Player> newPlayerAliases = getPlayerAliases(NewPlayer); List<Player> newPlayerAliases = GetPlayerAliases(NewPlayer);
foreach (Player aP in newPlayerAliases) // lets check their aliases foreach (Player aP in newPlayerAliases) // lets check their aliases
{ {
@ -135,7 +135,7 @@ namespace IW4MAdmin
continue; continue;
if (aP.Level == Player.Permission.Flagged) if (aP.Level == Player.Permission.Flagged)
NewPlayer.setLevel(Player.Permission.Flagged); NewPlayer.SetLevel(Player.Permission.Flagged);
Penalty B = IsBanned(aP); Penalty B = IsBanned(aP);
@ -398,9 +398,9 @@ namespace IW4MAdmin
if ((lastCount - playerCountStart).TotalMinutes > 4) if ((lastCount - playerCountStart).TotalMinutes > 4)
{ {
while (playerHistory.Count > 144) // 12 times a minute for 12 hours while (PlayerHistory.Count > 144) // 12 times a minute for 12 hours
playerHistory.Dequeue(); PlayerHistory.Dequeue();
playerHistory.Enqueue(new PlayerHistory(lastCount, ClientNum)); PlayerHistory.Enqueue(new PlayerHistory(lastCount, ClientNum));
playerCountStart = DateTime.Now; playerCountStart = DateTime.Now;
} }
@ -415,13 +415,13 @@ namespace IW4MAdmin
} }
//logFile = new IFile(); //logFile = new IFile();
if (l_size != logFile.getSize()) if (l_size != logFile.Length())
{ {
// this should be the longest running task // this should be the longest running task
await Task.FromResult(lines = logFile.Tail(12)); await Task.FromResult(lines = logFile.Tail(12));
if (lines != oldLines) if (lines != oldLines)
{ {
l_size = logFile.getSize(); l_size = logFile.Length();
int end; int end;
if (lines.Length == oldLines.Length) if (lines.Length == oldLines.Length)
end = lines.Length - 1; end = lines.Length - 1;
@ -458,7 +458,7 @@ namespace IW4MAdmin
} }
} }
oldLines = lines; oldLines = lines;
l_size = logFile.getSize(); l_size = logFile.Length();
} }
#if DEBUG == false #if DEBUG == false
catch (SharedLibrary.Exceptions.NetworkException) catch (SharedLibrary.Exceptions.NetworkException)
@ -486,6 +486,7 @@ namespace IW4MAdmin
var game = await this.GetDvarAsync<string>("fs_game"); var game = await this.GetDvarAsync<string>("fs_game");
var logfile = await this.GetDvarAsync<string>("g_log"); var logfile = await this.GetDvarAsync<string>("g_log");
var logsync = await this.GetDvarAsync<int>("g_logsync"); var logsync = await this.GetDvarAsync<int>("g_logsync");
var onelog = await this.GetDvarAsync<int>("iw4x_onelog");
try try
{ {
@ -512,22 +513,21 @@ namespace IW4MAdmin
// this DVAR isn't set until the a map is loaded // this DVAR isn't set until the a map is loaded
await this.SetDvarAsync("g_logsync", 1); await this.SetDvarAsync("g_logsync", 1);
await this.SetDvarAsync("g_log", "logs/games_mp.log"); await this.SetDvarAsync("g_log", "logs/games_mp.log");
Logger.WriteWarning("Game log file not properly initialized, restarting map...");
await this.ExecuteCommandAsync("map_restart"); await this.ExecuteCommandAsync("map_restart");
logfile = await this.GetDvarAsync<string>("g_log"); logfile = await this.GetDvarAsync<string>("g_log");
} }
#if DEBUG #if DEBUG
basepath.Value = @"\\tsclient\K\MW2"; basepath.Value = @"\\tsclient\K\MW2";
#endif #endif
string logPath = string.Empty; string logPath = (game.Value == "" || onelog.Value == 1) ? $"{basepath.Value.Replace("\\", "/")}/userraw/{logfile.Value}" : $"{basepath.Value.Replace("\\", "/")}/{game.Value}/{logfile.Value}";
if (game.Value == "")
logPath = $"{basepath.Value.Replace("\\", "/")}/userraw/{logfile.Value}";
else
logPath = $"{basepath.Value.Replace("\\", "/")}/{game.Value}/{logfile.Value}";
if (!File.Exists(logPath)) if (!File.Exists(logPath))
{ {
Logger.WriteError($"Gamelog {logPath} does not exist!"); Logger.WriteError($"Gamelog {logPath} does not exist!");
#if !DEBUG
throw new SharedLibrary.Exceptions.ServerException($"Invalid gamelog file {logPath}");
#endif
} }
logFile = new IFile(logPath); logFile = new IFile(logPath);
@ -565,23 +565,12 @@ namespace IW4MAdmin
if (E.Type == Event.GType.Kill) if (E.Type == Event.GType.Kill)
{ {
if (E.Origin == null)
{
Logger.WriteError("Kill event triggered, but no origin found!");
return;
}
if (E.Origin != E.Target) if (E.Origin != E.Target)
{
await ExecuteEvent(new Event(Event.GType.Death, E.Data, E.Target, null, this)); await ExecuteEvent(new Event(Event.GType.Death, E.Data, E.Target, null, this));
}
else // suicide/falling else // suicide/falling
{
Logger.WriteDebug(E.Origin.Name + " suicided...");
await ExecuteEvent(new Event(Event.GType.Death, "suicide", E.Target, null, this)); await ExecuteEvent(new Event(Event.GType.Death, "suicide", E.Target, null, this));
} }
}
if (E.Type == Event.GType.Say) if (E.Type == Event.GType.Say)
{ {
@ -730,7 +719,7 @@ namespace IW4MAdmin
if (Origin != null) if (Origin != null)
{ {
Target.setLevel(Player.Permission.Banned); Target.SetLevel(Player.Permission.Banned);
Penalty newBan = new Penalty(Penalty.Type.Ban, Target.lastOffense, Target.NetworkID, Origin.NetworkID, DateTime.Now, Target.IP); Penalty newBan = new Penalty(Penalty.Type.Ban, Target.lastOffense, Target.NetworkID, Origin.NetworkID, DateTime.Now, Target.IP);
await Task.Run(() => await Task.Run(() =>
@ -771,20 +760,18 @@ namespace IW4MAdmin
Manager.GetClientPenalties().RemovePenalty(PenaltyToRemove); Manager.GetClientPenalties().RemovePenalty(PenaltyToRemove);
Player P = Manager.GetClientDatabase().GetPlayer(Target.NetworkID, -1); Player P = Manager.GetClientDatabase().GetPlayer(Target.NetworkID, -1);
P.setLevel(Player.Permission.User); P.SetLevel(Player.Permission.User);
Manager.GetClientDatabase().UpdatePlayer(P); Manager.GetClientDatabase().UpdatePlayer(P);
}); });
} }
public override bool Reload() public override bool Reload()
{ {
try try
{ {
initMaps(); InitializeMaps();
initMessages(); InitializeAutoMessages();
initRules(); InitializeRules();
return true; return true;
} }
catch (Exception E) catch (Exception E)
@ -797,19 +784,18 @@ namespace IW4MAdmin
} }
} }
override public void initMacros() override public void InitializeTokens()
{ {
Manager.GetMessageTokens().Add(new MessageToken("TOTALPLAYERS", Manager.GetClientDatabase().TotalPlayers().ToString)); Manager.GetMessageTokens().Add(new MessageToken("TOTALPLAYERS", Manager.GetClientDatabase().TotalPlayers().ToString));
Manager.GetMessageTokens().Add(new MessageToken("VERSION", Program.Version.ToString)); Manager.GetMessageTokens().Add(new MessageToken("VERSION", Program.Version.ToString));
} }
override public void initCommands() override public void InitializeCommands()
{ {
foreach (Command C in PluginImporter.potentialCommands) foreach (Command C in PluginImporter.potentialCommands)
Manager.GetCommands().Add(C); Manager.GetCommands().Add(C);
Manager.GetCommands().Add(new Plugins("plugins", "view all loaded plugins. syntax: !plugins", "p", Player.Permission.Administrator, 0, false)); Manager.GetCommands().Add(new Plugins("plugins", "view all loaded plugins. syntax: !plugins", "p", Player.Permission.Administrator, 0, false));
} }
} }
} }

View File

@ -9,7 +9,7 @@ using SharedLibrary.Interfaces;
namespace IW4MAdmin namespace IW4MAdmin
{ {
public class Config : Serialize<Config> public class ServerConfig : Serialize<ServerConfig>
{ {
public string IP; public string IP;
public int Port; public int Port;
@ -21,7 +21,7 @@ namespace IW4MAdmin
return $"config/servers/{IP}_{Port}.cfg"; return $"config/servers/{IP}_{Port}.cfg";
} }
public static Config Generate() public static ServerConfig Generate()
{ {
string IP = String.Empty; string IP = String.Empty;
int Port = 0; int Port = 0;
@ -60,7 +60,7 @@ namespace IW4MAdmin
Console.Write("Enter server RCON password: "); Console.Write("Enter server RCON password: ");
Password = Console.ReadLine(); Password = Console.ReadLine();
var config = new Config() { IP = IP, Password = Password, Port = Port }; var config = new ServerConfig() { IP = IP, Password = Password, Port = Port };
config.Write(); config.Write();
Console.WriteLine("Config saved, add another? [y/n]:"); Console.WriteLine("Config saved, add another? [y/n]:");

View File

@ -19,19 +19,21 @@ namespace IW4MAdmin
var webScheduler = Kayak.KayakScheduler.Factory.Create(new Scheduler()); var webScheduler = Kayak.KayakScheduler.Factory.Create(new Scheduler());
webService = KayakServer.Factory.CreateHttp(new Request(), webScheduler); webService = KayakServer.Factory.CreateHttp(new Request(), webScheduler);
SharedLibrary.WebService.pageList.Add(new Pages()); SharedLibrary.WebService.PageList.Add(new Pages());
SharedLibrary.WebService.pageList.Add(new Homepage()); SharedLibrary.WebService.PageList.Add(new Homepage());
SharedLibrary.WebService.pageList.Add(new ServersJSON()); SharedLibrary.WebService.PageList.Add(new ServersJSON());
SharedLibrary.WebService.pageList.Add(new Penalties()); SharedLibrary.WebService.PageList.Add(new Penalties());
SharedLibrary.WebService.pageList.Add(new PenaltiesJSON()); SharedLibrary.WebService.PageList.Add(new PenaltiesJSON());
SharedLibrary.WebService.pageList.Add(new Players()); SharedLibrary.WebService.PageList.Add(new Players());
SharedLibrary.WebService.pageList.Add(new GetPlayer()); SharedLibrary.WebService.PageList.Add(new GetPlayer());
SharedLibrary.WebService.pageList.Add(new WebConsole()); SharedLibrary.WebService.PageList.Add(new WebConsole());
SharedLibrary.WebService.pageList.Add(new ConsoleJSON()); SharedLibrary.WebService.PageList.Add(new ConsoleJSON());
SharedLibrary.WebService.pageList.Add(new PubbansJSON()); SharedLibrary.WebService.PageList.Add(new PubbansJSON());
Thread scheduleThread = new Thread(() => { ScheduleThreadStart(webScheduler, webService); }); Thread scheduleThread = new Thread(() => { ScheduleThreadStart(webScheduler, webService); })
scheduleThread.Name = "Web Service Thread"; {
Name = "Web Service Thread"
};
scheduleThread.Start(); scheduleThread.Start();
return webScheduler; return webScheduler;
@ -66,16 +68,16 @@ namespace IW4MAdmin
public static HttpResponse GetPage(string path, System.Collections.Specialized.NameValueCollection queryset, IDictionary<string, string> headers) public static HttpResponse GetPage(string path, System.Collections.Specialized.NameValueCollection queryset, IDictionary<string, string> headers)
{ {
if (SharedLibrary.WebService.pageList == null || SharedLibrary.WebService.pageList.Count == 0) if (SharedLibrary.WebService.PageList == null || SharedLibrary.WebService.PageList.Count == 0)
return new HttpResponse() { content = "Error: page list not initialized!", contentType = "text/plaintext" }; return new HttpResponse() { content = "Error: page list not initialized!", contentType = "text/plaintext" };
if (path == null) if (path == null)
return new HttpResponse() { content = "Error: no path specified", contentType = "text/plaintext" }; return new HttpResponse() { content = "Error: no path specified", contentType = "text/plaintext" };
IPage requestedPage = SharedLibrary.WebService.pageList.Find(x => x.getPath().ToLower() == path.ToLower()); IPage requestedPage = SharedLibrary.WebService.PageList.Find(x => x.GetPath().ToLower() == path.ToLower());
if (requestedPage != null) if (requestedPage != null)
return requestedPage.getPage(queryset, headers); return requestedPage.GetPage(queryset, headers);
else else
{ {
if (System.IO.File.Exists(path.Replace("/", "\\").Substring(1))) if (System.IO.File.Exists(path.Replace("/", "\\").Substring(1)))
@ -85,10 +87,12 @@ namespace IW4MAdmin
if (path.Contains(".css")) if (path.Contains(".css"))
{ {
HttpResponse css = new HttpResponse(); HttpResponse css = new HttpResponse()
css.additionalHeaders = new Dictionary<string, string>(); {
css.content = f.getLines(); additionalHeaders = new Dictionary<string, string>(),
css.contentType = "text/css"; content = f.GetText(),
contentType = "text/css"
};
f.Close(); f.Close();
return css; return css;
@ -96,10 +100,12 @@ namespace IW4MAdmin
else if (path.Contains(".js")) else if (path.Contains(".js"))
{ {
HttpResponse css = new HttpResponse(); HttpResponse css = new HttpResponse()
css.additionalHeaders = new Dictionary<string, string>(); {
css.content = f.getLines(); additionalHeaders = new Dictionary<string, string>(),
css.contentType = "application/javascript"; content = f.GetText(),
contentType = "application/javascript"
};
f.Close(); f.Close();
return css; return css;
} }
@ -108,39 +114,40 @@ namespace IW4MAdmin
} }
requestedPage = new Error404(); requestedPage = new Error404();
return requestedPage.getPage(queryset, headers); return requestedPage.GetPage(queryset, headers);
} }
} }
} }
class Error404 : IPage class Error404 : IPage
{ {
public string getName() public string GetName()
{ {
return "404"; return "404";
} }
public string getPath() public string GetPath()
{ {
return ""; return "";
} }
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(); HttpResponse resp = new HttpResponse()
resp.additionalHeaders = new Dictionary<string, string>(); {
resp.content = "404 not found!"; additionalHeaders = new Dictionary<string, string>(),
resp.contentType = getContentType(); content = "404 not found!",
contentType = GetContentType()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "text/html"; return "text/html";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -148,24 +155,24 @@ namespace IW4MAdmin
class Homepage : HTMLPage class Homepage : HTMLPage
{ {
public override string getName() public override string GetName()
{ {
return "Home"; return "Home";
} }
public override string getPath() public override string GetPath()
{ {
return "/"; return "/";
} }
public override string getContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
StringBuilder S = new StringBuilder(); StringBuilder S = new StringBuilder();
S.Append(loadHeader()); S.Append(LoadHeader());
IFile p = new IFile("webfront\\main.html"); IFile p = new IFile("webfront\\main.html");
S.Append(p.getLines()); S.Append(p.GetText());
p.Close(); p.Close();
S.Append(loadFooter()); S.Append(LoadFooter());
return S.ToString(); return S.ToString();
} }
@ -173,37 +180,42 @@ namespace IW4MAdmin
class ServersJSON : IPage class ServersJSON : IPage
{ {
public string getName() public string GetName()
{ {
return "Servers"; return "Servers";
} }
public string getPath() public string GetPath()
{ {
return "/_servers"; return "/_servers";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
var info = new List<ServerInfo>(); var info = new List<ServerInfo>();
foreach (Server S in Manager.GetInstance().Servers) foreach (Server S in Manager.GetInstance().Servers)
{ {
ServerInfo eachServer = new ServerInfo(); ServerInfo eachServer = new ServerInfo()
eachServer.serverName = S.getName(); {
eachServer.serverPort = S.getPort(); serverName = S.Hostname,
eachServer.maxPlayers = S.MaxClients; serverPort = S.GetPort(),
eachServer.mapName = S.CurrentMap.Alias; maxPlayers = S.MaxClients,
eachServer.gameType = Utilities.gametypeLocalized(S.getGametype()); mapName = S.CurrentMap.Alias,
eachServer.currentPlayers = S.GetPlayersAsList().Count; gameType = Utilities.gametypeLocalized(S.Gametype),
eachServer.chatHistory = S.ChatHistory; currentPlayers = S.GetPlayersAsList().Count,
eachServer.players = new List<PlayerInfo>(); chatHistory = S.ChatHistory,
players = new List<PlayerInfo>()
};
foreach (Player P in S.GetPlayersAsList()) foreach (Player P in S.GetPlayersAsList())
{ {
PlayerInfo pInfo = new PlayerInfo(); PlayerInfo pInfo = new PlayerInfo()
pInfo.playerID = P.DatabaseID; {
pInfo.playerName = P.Name; playerID = P.DatabaseID,
pInfo.playerLevel = P.Level.ToString(); playerName = P.Name,
playerLevel = P.Level.ToString()
};
eachServer.players.Add(pInfo); eachServer.players.Add(pInfo);
} }
@ -211,19 +223,21 @@ namespace IW4MAdmin
} }
HttpResponse resp = new HttpResponse(); HttpResponse resp = new HttpResponse()
resp.contentType = getContentType(); {
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(info); contentType = GetContentType(),
resp.additionalHeaders = new Dictionary<string, string>(); content = Newtonsoft.Json.JsonConvert.SerializeObject(info),
additionalHeaders = new Dictionary<string, string>()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -231,35 +245,38 @@ namespace IW4MAdmin
class Info : IPage class Info : IPage
{ {
public string getName() public string GetName()
{ {
return "Info"; return "Info";
} }
public string getPath() public string GetPath()
{ {
return "/_info"; return "/_info";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
ApplicationInfo info = new ApplicationInfo(); ApplicationInfo info = new ApplicationInfo()
info.name = "IW4MAdmin"; {
info.version = Program.Version; name = "IW4MAdmin",
version = Program.Version
HttpResponse resp = new HttpResponse(); };
resp.contentType = getContentType(); HttpResponse resp = new HttpResponse()
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(info); {
resp.additionalHeaders = new Dictionary<string, string>(); contentType = GetContentType(),
content = Newtonsoft.Json.JsonConvert.SerializeObject(info),
additionalHeaders = new Dictionary<string, string>()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -268,27 +285,29 @@ namespace IW4MAdmin
class ConsoleJSON : IPage class ConsoleJSON : IPage
{ {
public string getName() public string GetName()
{ {
return "_Console"; return "_Console";
} }
public string getPath() public string GetPath()
{ {
return "/_console"; return "/_console";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
CommandInfo cmd = new CommandInfo(); CommandInfo cmd = new CommandInfo()
cmd.Result = new List<string>(); {
Result = new List<string>()
};
if (querySet["command"] != null) if (querySet["command"] != null)
{ {
if (querySet["server"] != null) if (querySet["server"] != null)
{ {
Server S = Manager.GetInstance().Servers.ToList().Find(x => (x.getPort().ToString() == querySet["server"])); Server S = Manager.GetInstance().Servers.ToList().Find(x => (x.GetPort().ToString() == querySet["server"]));
if (S != null) if (S != null)
{ {
@ -297,8 +316,10 @@ namespace IW4MAdmin
if (admin == null) if (admin == null)
admin = new Player("RestUser", "-1", -1, (int)Player.Permission.User); admin = new Player("RestUser", "-1", -1, (int)Player.Permission.User);
Event remoteEvent = new Event(Event.GType.Say, querySet["command"], admin, null, S); Event remoteEvent = new Event(Event.GType.Say, querySet["command"], admin, null, S)
remoteEvent.Remote = true; {
Remote = true
};
admin.lastEvent = remoteEvent; admin.lastEvent = remoteEvent;
S.ExecuteEvent(remoteEvent); S.ExecuteEvent(remoteEvent);
@ -318,19 +339,21 @@ namespace IW4MAdmin
cmd.Result.Add("No command entered."); cmd.Result.Add("No command entered.");
} }
HttpResponse resp = new HttpResponse(); HttpResponse resp = new HttpResponse()
resp.contentType = getContentType(); {
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(cmd); contentType = GetContentType(),
resp.additionalHeaders = new Dictionary<string, string>(); content = Newtonsoft.Json.JsonConvert.SerializeObject(cmd),
additionalHeaders = new Dictionary<string, string>()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -339,17 +362,17 @@ namespace IW4MAdmin
class PenaltiesJSON : IPage class PenaltiesJSON : IPage
{ {
public string getName() public string GetName()
{ {
return "Penalties"; return "Penalties";
} }
public string getPath() public string GetPath()
{ {
return "/_penalties"; return "/_penalties";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
int from = 0; int from = 0;
if (querySet["from"] != null) if (querySet["from"] != null)
@ -377,14 +400,18 @@ namespace IW4MAdmin
continue; continue;
if (admin == null) if (admin == null)
admin = new Player("Unknown", "-1", -1, (int)Player.Permission.Banned); admin = new Player("Unknown", "-1", -1, (int)Player.Permission.Banned);
PenaltyInfo pInfo = new PenaltyInfo();
pInfo.adminName = admin.Name; PenaltyInfo pInfo = new PenaltyInfo()
pInfo.adminLevel = admin.Level.ToString(); {
pInfo.penaltyReason = p.Reason; adminName = admin.Name,
pInfo.penaltyTime = SharedLibrary.Utilities.timePassed(p.When); adminLevel = admin.Level.ToString(),
pInfo.penaltyType = p.BType.ToString(); penaltyReason = p.Reason,
pInfo.playerName = penalized.Name; penaltyTime = SharedLibrary.Utilities.timePassed(p.When),
pInfo.playerID = penalized.DatabaseID; penaltyType = p.BType.ToString(),
playerName = penalized.Name,
playerID = penalized.DatabaseID
};
if (admin.NetworkID == penalized.NetworkID) if (admin.NetworkID == penalized.NetworkID)
{ {
pInfo.adminName = "IW4MAdmin"; pInfo.adminName = "IW4MAdmin";
@ -393,19 +420,21 @@ namespace IW4MAdmin
info.Add(pInfo); info.Add(pInfo);
} }
HttpResponse resp = new HttpResponse(); HttpResponse resp = new HttpResponse()
resp.contentType = getContentType(); {
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(info); contentType = GetContentType(),
resp.additionalHeaders = new Dictionary<string, string>(); content = Newtonsoft.Json.JsonConvert.SerializeObject(info),
additionalHeaders = new Dictionary<string, string>()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -413,26 +442,26 @@ namespace IW4MAdmin
class Penalties : HTMLPage class Penalties : HTMLPage
{ {
public override string getName() public override string GetName()
{ {
return "Penalties"; return "Penalties";
} }
public override string getPath() public override string GetPath()
{ {
return "/penalties"; return "/penalties";
} }
public override string getContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
StringBuilder S = new StringBuilder(); StringBuilder S = new StringBuilder();
S.Append(loadHeader()); S.Append(LoadHeader());
IFile penalities = new IFile("webfront\\penalties.html"); IFile penalities = new IFile("webfront\\penalties.html");
S.Append(penalities.getLines()); S.Append(penalities.GetText());
penalities.Close(); penalities.Close();
S.Append(loadFooter()); S.Append(LoadFooter());
return S.ToString(); return S.ToString();
} }
@ -440,26 +469,26 @@ namespace IW4MAdmin
class WebConsole : HTMLPage class WebConsole : HTMLPage
{ {
public override string getName() public override string GetName()
{ {
return "Console"; return "Console";
} }
public override string getPath() public override string GetPath()
{ {
return "/console"; return "/console";
} }
public override string getContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
StringBuilder S = new StringBuilder(); StringBuilder S = new StringBuilder();
S.Append(loadHeader()); S.Append(LoadHeader());
IFile console = new IFile("webfront\\console.html"); IFile console = new IFile("webfront\\console.html");
S.Append(console.getLines()); S.Append(console.GetText());
console.Close(); console.Close();
S.Append(loadFooter()); S.Append(LoadFooter());
return S.ToString(); return S.ToString();
} }
@ -467,26 +496,26 @@ namespace IW4MAdmin
class Players : HTMLPage class Players : HTMLPage
{ {
public override string getName() public override string GetName()
{ {
return "Players"; return "Players";
} }
public override string getPath() public override string GetPath()
{ {
return "/players"; return "/players";
} }
public override string getContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
StringBuilder S = new StringBuilder(); StringBuilder S = new StringBuilder();
S.Append(loadHeader()); S.Append(LoadHeader());
IFile penalities = new IFile("webfront\\players.html"); IFile penalities = new IFile("webfront\\players.html");
S.Append(penalities.getLines()); S.Append(penalities.GetText());
penalities.Close(); penalities.Close();
S.Append(loadFooter()); S.Append(LoadFooter());
return S.ToString(); return S.ToString();
} }
@ -494,31 +523,33 @@ namespace IW4MAdmin
class PubbansJSON : IPage class PubbansJSON : IPage
{ {
public string getName() public string GetName()
{ {
return "Public Ban List"; return "Public Ban List";
} }
public string getPath() public string GetPath()
{ {
return "/pubbans"; return "/pubbans";
} }
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(); HttpResponse resp = new HttpResponse()
resp.contentType = getContentType(); {
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(((Manager.GetInstance().GetClientPenalties()) as PenaltyList).AsChronoList(Convert.ToInt32(querySet["from"]), 15), Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter() }); contentType = GetContentType(),
resp.additionalHeaders = new Dictionary<string, string>(); content = Newtonsoft.Json.JsonConvert.SerializeObject(((Manager.GetInstance().GetClientPenalties()) as PenaltyList).AsChronoList(Convert.ToInt32(querySet["from"]), 15), Newtonsoft.Json.Formatting.Indented, new Newtonsoft.Json.JsonConverter[] { new Newtonsoft.Json.Converters.StringEnumConverter() }),
additionalHeaders = new Dictionary<string, string>()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -526,46 +557,49 @@ namespace IW4MAdmin
class Pages : IPage class Pages : IPage
{ {
public string getName() public string GetName()
{ {
return "Pages"; return "Pages";
} }
public string getPath() public string GetPath()
{ {
return "/pages"; return "/pages";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
List<PageInfo> pages = new List<PageInfo>(); List<PageInfo> pages = new List<PageInfo>();
foreach (var p in SharedLibrary.WebService.pageList.Where(x => x.isVisible())) foreach (var p in SharedLibrary.WebService.PageList.Where(x => x.Visible()))
{ {
if (p == this) if (p == this)
continue; continue;
PageInfo pi = new PageInfo(); PageInfo pi = new PageInfo()
pi.pagePath = p.getPath(); {
// pi.pageType = p.getPage(querySet, headers).contentType; pagePath = p.GetPath(),
pi.pageName = p.getName(); pageName = p.GetName(),
pi.visible = p.isVisible(); visible = p.Visible()
};
pages.Add(pi); pages.Add(pi);
} }
HttpResponse resp = new HttpResponse(); HttpResponse resp = new HttpResponse()
resp.contentType = getContentType(); {
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(pages); contentType = GetContentType(),
resp.additionalHeaders = new Dictionary<string, string>(); content = Newtonsoft.Json.JsonConvert.SerializeObject(pages),
additionalHeaders = new Dictionary<string, string>()
};
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -573,29 +607,30 @@ namespace IW4MAdmin
class GetPlayer : IPage class GetPlayer : IPage
{ {
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public string getPath() public string GetPath()
{ {
return "/getplayer"; return "/getplayer";
} }
public string getName() public string GetName()
{ {
return "GetPlayer"; return "GetPlayer";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
List<PlayerInfo> pInfo = new List<PlayerInfo>(); List<PlayerInfo> pInfo = new List<PlayerInfo>();
List<Player> matchedPlayers = new List<Player>(); List<Player> matchedPlayers = new List<Player>();
HttpResponse resp = new HttpResponse(); HttpResponse resp = new HttpResponse()
resp.contentType = getContentType(); {
resp.additionalHeaders = new Dictionary<string, string>(); contentType = GetContentType(),
additionalHeaders = new Dictionary<string, string>()
};
bool authed = Manager.GetInstance().GetClientDatabase().GetAdmins().FindAll(x => x.IP == querySet["IP"]).Count > 0; bool authed = Manager.GetInstance().GetClientDatabase().GetAdmins().FindAll(x => x.IP == querySet["IP"]).Count > 0;
bool recent = false; bool recent = false;
@ -625,15 +660,18 @@ namespace IW4MAdmin
foreach (var pp in matchedPlayers) foreach (var pp in matchedPlayers)
{ {
if (pp == null) continue; if (pp == null) continue;
PlayerInfo eachPlayer = new PlayerInfo();
eachPlayer.playerID = pp.DatabaseID; PlayerInfo eachPlayer = new PlayerInfo()
eachPlayer.playerIP = pp.IP; {
eachPlayer.playerLevel = pp.Level.ToString(); playerID = pp.DatabaseID,
eachPlayer.playerName = pp.Name; playerIP = pp.IP,
eachPlayer.playernpID = pp.NetworkID; playerLevel = pp.Level.ToString(),
eachPlayer.forumID = -1; playerName = pp.Name,
eachPlayer.authed = authed; playernpID = pp.NetworkID,
eachPlayer.showV2Features = false; forumID = -1,
authed = authed,
showV2Features = false
};
if (!recent) if (!recent)
{ {
@ -658,7 +696,7 @@ namespace IW4MAdmin
return resp; return resp;
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }

Binary file not shown.

View File

@ -15,17 +15,17 @@ namespace EventAPI
public RestEvent Event; public RestEvent Event;
} }
public string getName() public string GetName()
{ {
return "Events"; return "Events";
} }
public string getPath() public string GetPath()
{ {
return "/api/events"; return "/api/events";
} }
public HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers) public HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> headers)
{ {
bool shouldQuery = querySet.Get("status") != null; bool shouldQuery = querySet.Get("status") != null;
EventResponse requestedEvent = new EventResponse(); EventResponse requestedEvent = new EventResponse();
@ -34,15 +34,15 @@ namespace EventAPI
if (shouldQuery) if (shouldQuery)
{ {
StringBuilder s = new StringBuilder(); StringBuilder s = new StringBuilder();
foreach (var S in Events.activeServers) foreach (var S in Events.ActiveServers)
s.Append(String.Format("{0} has {1}/{4} players playing {2} on {3}\n", S.getName(), S.GetPlayersAsList().Count, Utilities.gametypeLocalized(S.getGametype()), S.CurrentMap.Name, S.MaxClients)); s.Append(String.Format("{0} has {1}/{4} players playing {2} on {3}\n", S.Hostname, S.GetPlayersAsList().Count, Utilities.gametypeLocalized(S.Gametype), S.CurrentMap.Name, S.MaxClients));
requestedEvent.Event = new RestEvent(RestEvent.eType.STATUS, RestEvent.eVersion.IW4MAdmin, s.ToString(), "Status", "", ""); requestedEvent.Event = new RestEvent(RestEvent.EventType.STATUS, RestEvent.EventVersion.IW4MAdmin, s.ToString(), "Status", "", "");
requestedEvent.eventCount = 1; requestedEvent.eventCount = 1;
} }
else if (Events.apiEvents.Count > 0) else if (Events.APIEvents.Count > 0)
{ {
requestedEvent.Event = Events.apiEvents.Dequeue(); requestedEvent.Event = Events.APIEvents.Dequeue();
requestedEvent.eventCount = 1; requestedEvent.eventCount = 1;
} }
@ -52,17 +52,17 @@ namespace EventAPI
} }
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(requestedEvent); resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(requestedEvent);
resp.contentType = getContentType(); resp.contentType = GetContentType();
resp.additionalHeaders = new Dictionary<string, string>(); resp.additionalHeaders = new Dictionary<string, string>();
return resp; return resp;
} }
public string getContentType() public string GetContentType()
{ {
return "application/json"; return "application/json";
} }
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
@ -70,8 +70,8 @@ namespace EventAPI
class Events : IPlugin class Events : IPlugin
{ {
public static Queue<RestEvent> apiEvents { get; private set; } public static Queue<RestEvent> APIEvents { get; private set; }
public static List<Server> activeServers; public static List<Server> ActiveServers;
DateTime lastClear; DateTime lastClear;
int flaggedMessages; int flaggedMessages;
@ -97,16 +97,16 @@ namespace EventAPI
public async Task OnLoadAsync() public async Task OnLoadAsync()
{ {
apiEvents = new Queue<RestEvent>(); APIEvents = new Queue<RestEvent>();
flaggedMessagesText = new List<string>(); flaggedMessagesText = new List<string>();
activeServers = new List<Server>(); ActiveServers = new List<Server>();
WebService.pageList.Add(new EventsJSON()); WebService.PageList.Add(new EventsJSON());
} }
public async Task OnUnloadAsync() public async Task OnUnloadAsync()
{ {
apiEvents.Clear(); APIEvents.Clear();
activeServers.Clear(); ActiveServers.Clear();
} }
public async Task OnTickAsync(Server S) public async Task OnTickAsync(Server S)
@ -118,29 +118,29 @@ namespace EventAPI
{ {
if (E.Type == Event.GType.Start) if (E.Type == Event.GType.Start)
{ {
activeServers.Add(S); ActiveServers.Add(S);
} }
if (E.Type == Event.GType.Stop) if (E.Type == Event.GType.Stop)
{ {
// fixme: this will be bad once FTP is working and there can be multiple servers on the same port. // fixme: this will be bad once FTP is working and there can be multiple servers on the same port.
activeServers.RemoveAll(s => s.getPort() == S.getPort()); ActiveServers.RemoveAll(s => s.GetPort() == S.GetPort());
} }
if (E.Type == Event.GType.Connect) if (E.Type == Event.GType.Connect)
{ {
addRestEvent(new RestEvent(RestEvent.eType.NOTIFICATION, RestEvent.eVersion.IW4MAdmin, E.Origin.Name + " has joined " + S.getName(), E.Type.ToString(), S.getName(), E.Origin.Name)); AddRestEvent(new RestEvent(RestEvent.EventType.NOTIFICATION, RestEvent.EventVersion.IW4MAdmin, E.Origin.Name + " has joined " + S.Hostname, E.Type.ToString(), S.Hostname, E.Origin.Name));
} }
if (E.Type == Event.GType.Disconnect) if (E.Type == Event.GType.Disconnect)
{ {
addRestEvent(new RestEvent(RestEvent.eType.NOTIFICATION, RestEvent.eVersion.IW4MAdmin, E.Origin.Name + " has left " + S.getName(), E.Type.ToString(), S.getName(), E.Origin.Name)); AddRestEvent(new RestEvent(RestEvent.EventType.NOTIFICATION, RestEvent.EventVersion.IW4MAdmin, E.Origin.Name + " has left " + S.Hostname, E.Type.ToString(), S.Hostname, E.Origin.Name));
} }
if (E.Type == Event.GType.Say) if (E.Type == Event.GType.Say)
{ {
if (E.Data.Length != 0 && E.Data[0] != '!') if (E.Data.Length != 0 && E.Data[0] != '!')
addRestEvent(new RestEvent(RestEvent.eType.NOTIFICATION, RestEvent.eVersion.IW4MAdmin, E.Data, "Chat", E.Origin.Name, "")); AddRestEvent(new RestEvent(RestEvent.EventType.NOTIFICATION, RestEvent.EventVersion.IW4MAdmin, E.Data, "Chat", E.Origin.Name, ""));
} }
if (E.Type == Event.GType.Say && E.Origin.Level < Player.Permission.Moderator) if (E.Type == Event.GType.Say && E.Origin.Level < Player.Permission.Moderator)
@ -158,8 +158,8 @@ namespace EventAPI
{ {
await E.Owner.Broadcast("If you suspect someone of ^5CHEATING ^7use the ^5!report ^7command"); await E.Owner.Broadcast("If you suspect someone of ^5CHEATING ^7use the ^5!report ^7command");
addRestEvent(new RestEvent(RestEvent.eType.ALERT, RestEvent.eVersion.IW4MAdmin, "Chat indicates there may be a cheater", "Alert", E.Owner.getName(), "")); AddRestEvent(new RestEvent(RestEvent.EventType.ALERT, RestEvent.EventVersion.IW4MAdmin, "Chat indicates there may be a cheater", "Alert", E.Owner.Hostname, ""));
addRestEvent(new RestEvent(RestEvent.eType.NOTIFICATION, RestEvent.eVersion.IW4MAdmin, String.Join("\n", flaggedMessagesText), "Chat Monitor", E.Owner.getName(), "")); AddRestEvent(new RestEvent(RestEvent.EventType.NOTIFICATION, RestEvent.EventVersion.IW4MAdmin, String.Join("\n", flaggedMessagesText), "Chat Monitor", E.Owner.Hostname, ""));
flaggedMessages = 0; flaggedMessages = 0;
} }
@ -172,11 +172,11 @@ namespace EventAPI
} }
} }
public static void addRestEvent(RestEvent E) public static void AddRestEvent(RestEvent E)
{ {
if (apiEvents.Count > 10) if (APIEvents.Count > 10)
apiEvents.Dequeue(); APIEvents.Dequeue();
apiEvents.Enqueue(E); APIEvents.Enqueue(E);
} }
} }
} }

View File

@ -343,26 +343,26 @@ namespace MessageBoard.Forum
forumPages.Add(logout); forumPages.Add(logout);
forumPages.Add(stats); forumPages.Add(stats);
SharedLibrary.WebService.pageList.Add(login); SharedLibrary.WebService.PageList.Add(login);
SharedLibrary.WebService.pageList.Add(loginJSON); SharedLibrary.WebService.PageList.Add(loginJSON);
SharedLibrary.WebService.pageList.Add(register); SharedLibrary.WebService.PageList.Add(register);
SharedLibrary.WebService.pageList.Add(registerJSON); SharedLibrary.WebService.PageList.Add(registerJSON);
SharedLibrary.WebService.pageList.Add(userinfoJSON); SharedLibrary.WebService.PageList.Add(userinfoJSON);
SharedLibrary.WebService.pageList.Add(viewUser); SharedLibrary.WebService.PageList.Add(viewUser);
SharedLibrary.WebService.pageList.Add(userCP); SharedLibrary.WebService.PageList.Add(userCP);
SharedLibrary.WebService.pageList.Add(updateUserJSON); SharedLibrary.WebService.PageList.Add(updateUserJSON);
SharedLibrary.WebService.pageList.Add(categoriesJSON); SharedLibrary.WebService.PageList.Add(categoriesJSON);
SharedLibrary.WebService.pageList.Add(category); SharedLibrary.WebService.PageList.Add(category);
SharedLibrary.WebService.pageList.Add(categorythreadsJSON); SharedLibrary.WebService.PageList.Add(categorythreadsJSON);
SharedLibrary.WebService.pageList.Add(home); SharedLibrary.WebService.PageList.Add(home);
SharedLibrary.WebService.pageList.Add(recentthreadsJSON); SharedLibrary.WebService.PageList.Add(recentthreadsJSON);
SharedLibrary.WebService.pageList.Add(postthread); SharedLibrary.WebService.PageList.Add(postthread);
SharedLibrary.WebService.pageList.Add(postthreadJSON); SharedLibrary.WebService.PageList.Add(postthreadJSON);
SharedLibrary.WebService.pageList.Add(editthreadJSON); SharedLibrary.WebService.PageList.Add(editthreadJSON);
SharedLibrary.WebService.pageList.Add(threadJSON); SharedLibrary.WebService.PageList.Add(threadJSON);
SharedLibrary.WebService.pageList.Add(viewthread); SharedLibrary.WebService.PageList.Add(viewthread);
SharedLibrary.WebService.pageList.Add(logout); SharedLibrary.WebService.PageList.Add(logout);
SharedLibrary.WebService.pageList.Add(stats); SharedLibrary.WebService.PageList.Add(stats);
guestRank = database.getRank("Guest"); guestRank = database.getRank("Guest");
UserRank = database.getRank("User"); UserRank = database.getRank("User");
@ -375,7 +375,7 @@ namespace MessageBoard.Forum
//session logouts //session logouts
//checkme //checkme
foreach (var page in forumPages) foreach (var page in forumPages)
SharedLibrary.WebService.pageList.Remove(page); SharedLibrary.WebService.PageList.Remove(page);
} }
} }
@ -386,22 +386,22 @@ namespace MessageBoard.Forum
{ {
protected Session currentSession; protected Session currentSession;
public bool isVisible() public bool Visible()
{ {
return false; return false;
} }
public virtual string getPath() public virtual string GetPath()
{ {
return "/forum"; return "/forum";
} }
public string getName() public string GetName()
{ {
return "JSONPage"; return "JSONPage";
} }
public virtual HttpResponse getPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> requestHeaders) public virtual HttpResponse GetPage(System.Collections.Specialized.NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
HttpResponse resp = new HttpResponse(); HttpResponse resp = new HttpResponse();
resp.contentType = "application/json"; resp.contentType = "application/json";
@ -431,22 +431,22 @@ namespace MessageBoard.Forum
abstract public class ForumPage : HTMLPage abstract public class ForumPage : HTMLPage
{ {
public ForumPage(bool visible) : base(visible) { } public ForumPage(bool visible) : base(visible) { }
public abstract override string getName(); public abstract override string GetName();
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/forum"; return base.GetPath() + "/forum";
} }
public override Dictionary<string, string> getHeaders(IDictionary<string, string> requestHeaders) public override Dictionary<string, string> GetHeaders(IDictionary<string, string> requestHeaders)
{ {
return base.getHeaders(requestHeaders); return base.GetHeaders(requestHeaders);
} }
protected string templatation(string bodyContent) protected string templatation(string bodyContent)
{ {
StringBuilder S = new StringBuilder(); StringBuilder S = new StringBuilder();
S.Append(base.loadHeader()); S.Append(base.LoadHeader());
S.Append(bodyContent); S.Append(bodyContent);
S.Append(base.loadFooter()); S.Append(base.LoadFooter());
return S.ToString(); return S.ToString();
} }
@ -459,19 +459,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum"; return "Forum";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/login"; return base.GetPath() + "/login";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string,string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string,string> headers)
{ {
return templatation(loadFile("forum\\login.html")); return templatation(LoadFile("forum\\login.html"));
} }
} }
@ -482,19 +482,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Register"; return "Register";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/register"; return base.GetPath() + "/register";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\register.html"); string content = LoadFile("forum\\register.html");
return templatation(content); return templatation(content);
} }
} }
@ -506,19 +506,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - Home"; return "Forum - Home";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/home"; return base.GetPath() + "/home";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\home.html"); string content = LoadFile("forum\\home.html");
return templatation(content); return templatation(content);
} }
} }
@ -530,19 +530,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - Post New Thread"; return "Forum - Post New Thread";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/postthread"; return base.GetPath() + "/postthread";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\postthread.html"); string content = LoadFile("forum\\postthread.html");
return templatation(content); return templatation(content);
} }
} }
@ -554,19 +554,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - Category View"; return "Forum - Category View";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/category"; return base.GetPath() + "/category";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\category.html"); string content = LoadFile("forum\\category.html");
return templatation(content); return templatation(content);
} }
} }
@ -578,19 +578,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - View User"; return "Forum - View User";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/user"; return base.GetPath() + "/user";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\user.html"); string content = LoadFile("forum\\user.html");
return templatation(content); return templatation(content);
} }
} }
@ -602,19 +602,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - User Control Panel"; return "Forum - User Control Panel";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/usercp"; return base.GetPath() + "/usercp";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\usercp.html"); string content = LoadFile("forum\\usercp.html");
return templatation(content); return templatation(content);
} }
} }
@ -626,19 +626,19 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - View Thread"; return "Forum - View Thread";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/thread"; return base.GetPath() + "/thread";
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = loadFile("forum\\thread.html"); string content = LoadFile("forum\\thread.html");
return templatation(content); return templatation(content);
} }
} }
@ -650,23 +650,23 @@ namespace MessageBoard.Forum
} }
public override string getName() public override string GetName()
{ {
return "Forum - Log Out"; return "Forum - Log Out";
} }
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/logout"; return base.GetPath() + "/logout";
} }
public override Dictionary<string, string> getHeaders(IDictionary<string, string> requestHeaders) public override Dictionary<string, string> GetHeaders(IDictionary<string, string> requestHeaders)
{ {
Plugin.Main.forum.removeSession(requestHeaders["Cookie"].Split('=')[1]); Plugin.Main.forum.removeSession(requestHeaders["Cookie"].Split('=')[1]);
return new Dictionary<string, string>() { { "Set-Cookie", "IW4MAdmin_ForumSession=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT" } }; return new Dictionary<string, string>() { { "Set-Cookie", "IW4MAdmin_ForumSession=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT" } };
} }
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers) public override string GetContent(NameValueCollection querySet, IDictionary<string, string> headers)
{ {
string content = @"<meta http-equiv='refresh' content='0; url = login' />"; string content = @"<meta http-equiv='refresh' content='0; url = login' />";
return templatation(content); return templatation(content);
@ -675,18 +675,18 @@ namespace MessageBoard.Forum
public class RegisterJSON : JSONPage public class RegisterJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_register"; return base.GetPath() + "/_register";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
var result = new ActionResponse(); var result = new ActionResponse();
result.success = false; result.success = false;
result.destination = base.getPath() + "/error"; result.destination = base.GetPath() + "/error";
try { try {
@ -723,7 +723,7 @@ namespace MessageBoard.Forum
else else
{ {
result.destination = base.getPath() + "/home"; result.destination = base.GetPath() + "/home";
result.success = true; result.success = true;
result.errorCode = Manager.ErrorCode.NO_ERROR; result.errorCode = Manager.ErrorCode.NO_ERROR;
} }
@ -742,14 +742,14 @@ namespace MessageBoard.Forum
public class userinfoJSON : JSONPage public class userinfoJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_userinfo"; return base.GetPath() + "/_userinfo";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
UserInfo info = new UserInfo(); UserInfo info = new UserInfo();
bool validUserSelection = true; bool validUserSelection = true;
@ -800,14 +800,14 @@ namespace MessageBoard.Forum
public class updateUserJSON : JSONPage public class updateUserJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_updateuser"; return base.GetPath() + "/_updateuser";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
var aResp = new ActionResponse(); var aResp = new ActionResponse();
bool passwordUpdateRequest = false; bool passwordUpdateRequest = false;
@ -892,14 +892,14 @@ namespace MessageBoard.Forum
public class LoginJSON : JSONPage public class LoginJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_login"; return base.GetPath() + "/_login";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
ActionResponse aResp = new ActionResponse(); ActionResponse aResp = new ActionResponse();
aResp.success = false; aResp.success = false;
@ -926,14 +926,14 @@ namespace MessageBoard.Forum
public class categoriesJSON : JSONPage public class categoriesJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_categories"; return base.GetPath() + "/_categories";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
var categories = Plugin.Main.forum.getAllCategories(); var categories = Plugin.Main.forum.getAllCategories();
@ -944,14 +944,14 @@ namespace MessageBoard.Forum
public class recentthreadsJSON : JSONPage public class recentthreadsJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_recentthreads"; return base.GetPath() + "/_recentthreads";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
try try
{ {
@ -986,14 +986,14 @@ namespace MessageBoard.Forum
public class categorythreadsJSON : JSONPage public class categorythreadsJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_categorythreads"; return base.GetPath() + "/_categorythreads";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
var aResp = new ActionResponse(); var aResp = new ActionResponse();
try try
@ -1033,14 +1033,14 @@ namespace MessageBoard.Forum
public class threadJSON : JSONPage public class threadJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_thread"; return base.GetPath() + "/_thread";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
var aResp = new ActionResponse(); var aResp = new ActionResponse();
aResp.success = false; aResp.success = false;
aResp.errorCode = Manager.ErrorCode.NO_ERROR; aResp.errorCode = Manager.ErrorCode.NO_ERROR;
@ -1096,14 +1096,14 @@ namespace MessageBoard.Forum
public class editthreadJSON : JSONPage public class editthreadJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_editthread"; return base.GetPath() + "/_editthread";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
var aResp = new ActionResponse(); var aResp = new ActionResponse();
aResp.success = false; aResp.success = false;
aResp.errorCode = Manager.ErrorCode.NO_ERROR; aResp.errorCode = Manager.ErrorCode.NO_ERROR;
@ -1237,14 +1237,14 @@ namespace MessageBoard.Forum
public class postthreadJSON : JSONPage public class postthreadJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_postthread"; return base.GetPath() + "/_postthread";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
ActionResponse aResp = new ActionResponse(); ActionResponse aResp = new ActionResponse();
if (currentSession.sessionUser.ranking.equivalentRank < Player.Permission.Trusted) if (currentSession.sessionUser.ranking.equivalentRank < Player.Permission.Trusted)
@ -1316,14 +1316,14 @@ namespace MessageBoard.Forum
public class StatsJSON : JSONPage public class StatsJSON : JSONPage
{ {
public override string getPath() public override string GetPath()
{ {
return base.getPath() + "/_stats"; return base.GetPath() + "/_stats";
} }
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders) public override HttpResponse GetPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{ {
var resp = base.getPage(querySet, requestHeaders); var resp = base.GetPage(querySet, requestHeaders);
StatView stats = new StatView(); StatView stats = new StatView();
stats.onlineUsers = new List<User>(); stats.onlineUsers = new List<User>();

Binary file not shown.

View File

@ -26,13 +26,13 @@ namespace StatsPlugin
if (E.Target != null) if (E.Target != null)
{ {
pStats = Stats.statLists.Find(x => x.Port == E.Owner.getPort()).playerStats.GetStats(E.Target); pStats = Stats.statLists.Find(x => x.Port == E.Owner.GetPort()).playerStats.GetStats(E.Target);
statLine = String.Format("^5{0} ^7KILLS | ^5{1} ^7DEATHS | ^5{2} ^7KDR | ^5{3} ^7SKILL", pStats.Kills, pStats.Deaths, pStats.KDR, pStats.Skill); statLine = String.Format("^5{0} ^7KILLS | ^5{1} ^7DEATHS | ^5{2} ^7KDR | ^5{3} ^7SKILL", pStats.Kills, pStats.Deaths, pStats.KDR, pStats.Skill);
} }
else else
{ {
pStats = Stats.statLists.Find(x => x.Port == E.Owner.getPort()).playerStats.GetStats(E.Origin); pStats = Stats.statLists.Find(x => x.Port == E.Owner.GetPort()).playerStats.GetStats(E.Origin);
statLine = String.Format("^5{0} ^7KILLS | ^5{1} ^7DEATHS | ^5{2} ^7KDR | ^5{3} ^7SKILL", pStats.Kills, pStats.Deaths, pStats.KDR, pStats.Skill); statLine = String.Format("^5{0} ^7KILLS | ^5{1} ^7DEATHS | ^5{2} ^7KDR | ^5{3} ^7SKILL", pStats.Kills, pStats.Deaths, pStats.KDR, pStats.Skill);
} }
@ -58,7 +58,7 @@ namespace StatsPlugin
public override async Task ExecuteAsync(Event E) public override async Task ExecuteAsync(Event E)
{ {
List<KeyValuePair<String, PlayerStats>> pStats = Stats.statLists.Find(x => x.Port == E.Owner.getPort()).playerStats.GetTopStats(); List<KeyValuePair<String, PlayerStats>> pStats = Stats.statLists.Find(x => x.Port == E.Owner.GetPort()).playerStats.GetTopStats();
StringBuilder msgBlder = new StringBuilder(); StringBuilder msgBlder = new StringBuilder();
await E.Origin.Tell("^5--Top Players--"); await E.Origin.Tell("^5--Top Players--");
@ -79,13 +79,13 @@ namespace StatsPlugin
public override async Task ExecuteAsync(Event E) public override async Task ExecuteAsync(Event E)
{ {
var stats = Stats.statLists.Find(x => x.Port == E.Owner.getPort()).playerStats.GetStats(E.Origin); var stats = Stats.statLists.Find(x => x.Port == E.Owner.GetPort()).playerStats.GetStats(E.Origin);
stats.Deaths = 0; stats.Deaths = 0;
stats.Kills = 0; stats.Kills = 0;
stats.scorePerMinute = 1.0; stats.scorePerMinute = 1.0;
stats.Skill = 1; stats.Skill = 1;
stats.KDR = 0.0; stats.KDR = 0.0;
await Task.Run(() => { Stats.statLists.Find(x => x.Port == E.Owner.getPort()).playerStats.UpdateStats(E.Origin, stats); }); await Task.Run(() => { Stats.statLists.Find(x => x.Port == E.Owner.GetPort()).playerStats.UpdateStats(E.Origin, stats); });
await E.Origin.Tell("Your stats have been reset"); await E.Origin.Tell("Your stats have been reset");
} }
} }
@ -152,7 +152,7 @@ namespace StatsPlugin
{ {
if (E.Type == Event.GType.Start) if (E.Type == Event.GType.Start)
{ {
statLists.Add(new StatTracking(S.getPort())); statLists.Add(new StatTracking(S.GetPort()));
if (statLists.Count == 1) if (statLists.Count == 1)
{ {
S.Manager.GetMessageTokens().Add(new MessageToken("TOTALKILLS", GetTotalKills)); S.Manager.GetMessageTokens().Add(new MessageToken("TOTALKILLS", GetTotalKills));
@ -162,17 +162,17 @@ namespace StatsPlugin
if (E.Type == Event.GType.Stop) if (E.Type == Event.GType.Stop)
{ {
statLists.RemoveAll(x => x.Port == S.getPort()); statLists.RemoveAll(x => x.Port == S.GetPort());
} }
if (E.Type == Event.GType.Connect) if (E.Type == Event.GType.Connect)
{ {
ResetCounters(E.Origin.ClientID, S.getPort()); ResetCounters(E.Origin.ClientID, S.GetPort());
PlayerStats checkForTrusted = statLists.Find(x => x.Port == S.getPort()).playerStats.GetStats(E.Origin); PlayerStats checkForTrusted = statLists.Find(x => x.Port == S.GetPort()).playerStats.GetStats(E.Origin);
if (checkForTrusted.TotalPlayTime >= 4320 && E.Origin.Level < Player.Permission.Trusted) if (checkForTrusted.TotalPlayTime >= 4320 && E.Origin.Level < Player.Permission.Trusted)
{ {
E.Origin.setLevel(Player.Permission.Trusted); E.Origin.SetLevel(Player.Permission.Trusted);
E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Origin); E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Origin);
await E.Origin.Tell("Congratulations, you are now a ^5trusted ^7player! Type ^5!help ^7to view new commands."); await E.Origin.Tell("Congratulations, you are now a ^5trusted ^7player! Type ^5!help ^7to view new commands.");
await E.Origin.Tell("You earned this by playing for ^53 ^7full days!"); await E.Origin.Tell("You earned this by playing for ^53 ^7full days!");
@ -187,8 +187,8 @@ namespace StatsPlugin
if (P == null) if (P == null)
continue; continue;
CalculateAndSaveSkill(P, statLists.Find(x =>x.Port == S.getPort())); CalculateAndSaveSkill(P, statLists.Find(x =>x.Port == S.GetPort()));
ResetCounters(P.ClientID, S.getPort()); ResetCounters(P.ClientID, S.GetPort());
E.Owner.Logger.WriteInfo("Updated skill for client #" + P.DatabaseID); E.Owner.Logger.WriteInfo("Updated skill for client #" + P.DatabaseID);
//E.Owner.Log.Write(String.Format("\r\nJoin: {0}\r\nInactive Minutes: {1}\r\nnewPlayTime: {2}\r\nnewSPM: {3}\r\nkdrWeight: {4}\r\nMultiplier: {5}\r\nscoreWeight: {6}\r\nnewSkillFactor: {7}\r\nprojectedNewSkill: {8}\r\nKills: {9}\r\nDeaths: {10}", connectionTime[P.clientID].ToShortTimeString(), inactiveMinutes[P.clientID], newPlayTime, newSPM, kdrWeight, Multiplier, scoreWeight, newSkillFactor, disconnectStats.Skill, disconnectStats.Kills, disconnectStats.Deaths)); //E.Owner.Log.Write(String.Format("\r\nJoin: {0}\r\nInactive Minutes: {1}\r\nnewPlayTime: {2}\r\nnewSPM: {3}\r\nkdrWeight: {4}\r\nMultiplier: {5}\r\nscoreWeight: {6}\r\nnewSkillFactor: {7}\r\nprojectedNewSkill: {8}\r\nKills: {9}\r\nDeaths: {10}", connectionTime[P.clientID].ToShortTimeString(), inactiveMinutes[P.clientID], newPlayTime, newSPM, kdrWeight, Multiplier, scoreWeight, newSkillFactor, disconnectStats.Skill, disconnectStats.Kills, disconnectStats.Deaths));
@ -197,8 +197,8 @@ namespace StatsPlugin
if (E.Type == Event.GType.Disconnect) if (E.Type == Event.GType.Disconnect)
{ {
CalculateAndSaveSkill(E.Origin, statLists.Find(x=>x.Port == S.getPort())); CalculateAndSaveSkill(E.Origin, statLists.Find(x=>x.Port == S.GetPort()));
ResetCounters(E.Origin.ClientID, S.getPort()); ResetCounters(E.Origin.ClientID, S.GetPort());
E.Owner.Logger.WriteInfo("Updated skill for disconnecting client #" + E.Origin.DatabaseID); E.Owner.Logger.WriteInfo("Updated skill for disconnecting client #" + E.Origin.DatabaseID);
} }
@ -208,7 +208,7 @@ namespace StatsPlugin
return; return;
Player Killer = E.Origin; Player Killer = E.Origin;
StatTracking curServer = statLists.Find(x => x.Port == S.getPort()); StatTracking curServer = statLists.Find(x => x.Port == S.GetPort());
PlayerStats killerStats = curServer.playerStats.GetStats(Killer); PlayerStats killerStats = curServer.playerStats.GetStats(Killer);
@ -237,7 +237,7 @@ namespace StatsPlugin
return; return;
Player Victim = E.Origin; Player Victim = E.Origin;
StatTracking curServer = statLists.Find(x => x.Port == S.getPort()); StatTracking curServer = statLists.Find(x => x.Port == S.GetPort());
PlayerStats victimStats = curServer.playerStats.GetStats(Victim); PlayerStats victimStats = curServer.playerStats.GetStats(Victim);
victimStats.Deaths++; victimStats.Deaths++;

View File

@ -27,7 +27,7 @@ namespace Votemap_Plugin
/// <param name="E">This is the `say` event that comes from the server</param> /// <param name="E">This is the `say` event that comes from the server</param>
public override async Task ExecuteAsync(Event E) public override async Task ExecuteAsync(Event E)
{ {
var voting = Vote.getServerVotes(E.Owner.getPort()); var voting = Vote.getServerVotes(E.Owner.GetPort());
// we only want to allow a vote during a vote session // we only want to allow a vote during a vote session
if (voting.voteInSession) if (voting.voteInSession)
@ -60,7 +60,7 @@ namespace Votemap_Plugin
public override async Task ExecuteAsync(Event E) public override async Task ExecuteAsync(Event E)
{ {
var voting = Vote.getServerVotes(E.Owner.getPort()); var voting = Vote.getServerVotes(E.Owner.GetPort());
if (voting.voteInSession) if (voting.voteInSession)
{ {
@ -222,7 +222,7 @@ namespace Votemap_Plugin
/// <param name="S"></param> /// <param name="S"></param>
public async Task OnTickAsync(Server S) public async Task OnTickAsync(Server S)
{ {
var serverVotes = getServerVotes(S.getPort()); var serverVotes = getServerVotes(S.GetPort());
if (serverVotes != null) if (serverVotes != null)
{ {
@ -282,17 +282,17 @@ namespace Votemap_Plugin
{ {
if (E.Type == Event.GType.Start) if (E.Type == Event.GType.Start)
{ {
serverVotingList.Add(new ServerVoting(S.getPort())); serverVotingList.Add(new ServerVoting(S.GetPort()));
} }
if (E.Type == Event.GType.Stop) if (E.Type == Event.GType.Stop)
{ {
serverVotingList.RemoveAll(x => x.serverID == S.getPort()); serverVotingList.RemoveAll(x => x.serverID == S.GetPort());
} }
if (E.Type == Event.GType.MapEnd || E.Type == Event.GType.MapChange) if (E.Type == Event.GType.MapEnd || E.Type == Event.GType.MapChange)
{ {
var serverVotes = getServerVotes(S.getPort()); var serverVotes = getServerVotes(S.GetPort());
serverVotes.voteList.Clear(); serverVotes.voteList.Clear();
serverVotes.voteTimeStart = DateTime.MinValue; serverVotes.voteTimeStart = DateTime.MinValue;
serverVotes.loadStartTime = DateTime.Now; serverVotes.loadStartTime = DateTime.Now;

View File

@ -2,7 +2,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Linq; using System.Linq;
using SharedLibrary;
using SharedLibrary.Network; using SharedLibrary.Network;
using System.Threading.Tasks; 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 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) public override async Task ExecuteAsync(Event E)
{ {
if (E.Owner.Manager.GetClientDatabase().GetOwner() == null) 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!"); await E.Origin.Tell("Congratulations, you have claimed ownership of this server!");
E.Owner.owner = E.Origin; E.Owner.owner = E.Origin;
E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Origin); E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Origin);
@ -74,7 +73,7 @@ namespace SharedLibrary.Commands
if (E.Origin.Level > E.Target.Level) if (E.Origin.Level > E.Target.Level)
await E.Target.Kick(E.Target.lastOffense, E.Origin); await E.Target.Kick(E.Target.lastOffense, E.Origin);
else 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) 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) if (newPerm == Player.Permission.Owner && E.Origin.Level != Player.Permission.Console)
newPerm = Player.Permission.Banned; newPerm = Player.Permission.Banned;
bool playerInOtherServer = false;
if (newPerm > Player.Permission.Banned) if (newPerm > Player.Permission.Banned)
{ {
E.Target.setLevel(newPerm); var ActiveClient = E.Owner.Manager.GetActiveClients().First(p => p.NetworkID == E.Target.NetworkID);
// prevent saving of old permissions on disconnect ActiveClient?.SetLevel(newPerm);
// 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;
}
}
}
if (!playerInOtherServer) await ActiveClient?.Tell("Congratulations! You have been promoted to ^3" + newPerm);
await E.Target.Tell("Congratulations! You have been promoted to ^3" + newPerm); await E.Origin.Tell($"{E.Target.Name} was successfully promoted!");
await E.Origin.Tell(E.Target.Name + " was successfully promoted!");
//NEEED TO MOVE E.Target.SetLevel(newPerm);
E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Target); E.Owner.Manager.GetClientDatabase().UpdatePlayer(E.Target);
} }
@ -398,7 +381,7 @@ namespace SharedLibrary.Commands
foreach (Player P in db_players) 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); await E.Origin.Tell(mesg);
} }
} }
@ -516,14 +499,14 @@ namespace SharedLibrary.Commands
if (E.Target.Level == Player.Permission.Flagged) 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); await E.Origin.Tell("You have ^5unflagged ^7" + E.Target.Name);
} }
else else
{ {
E.Data = Utilities.RemoveWords(E.Data, 1); 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)); 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); 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 String Message { get; private set; }
public DateTime Time { get; private set; } public DateTime Time { get; private set; }
public string Name; public string Name;
@ -30,7 +24,7 @@ namespace SharedLibrary
[Serializable] [Serializable]
public struct RestEvent 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; Type = Ty;
Version = V; Version = V;
@ -42,20 +36,20 @@ namespace SharedLibrary
ID = Math.Abs(DateTime.Now.GetHashCode()); ID = Math.Abs(DateTime.Now.GetHashCode());
} }
public enum eType public enum EventType
{ {
NOTIFICATION, NOTIFICATION,
STATUS, STATUS,
ALERT, ALERT,
} }
public enum eVersion public enum EventVersion
{ {
IW4MAdmin IW4MAdmin
} }
public eType Type; public EventType Type;
public eVersion Version; public EventVersion Version;
public string Message; public string Message;
public string Title; public string Title;
public string Origin; public string Origin;

View File

@ -10,86 +10,30 @@ namespace SharedLibrary
{ {
public IFile(String fileName) public IFile(String fileName)
{ {
//Not safe for directories with more than one folder but meh Name = fileName;
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)); Handle = new StreamReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
sze = Handle.BaseStream.Length; sze = Handle.BaseStream.Length;
} }
catch public long Length()
{
//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));
sze = Handle.BaseStream.Length;
}
public long getSize()
{ {
sze = Handle.BaseStream.Length; sze = Handle.BaseStream.Length;
return sze; 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() public void Close()
{ {
if (Handle != null) Handle?.Close();
Handle.Close();
if (writeHandle != null)
writeHandle.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) public String[] Tail(int lineCount)
@ -122,8 +66,6 @@ namespace SharedLibrary
private long sze; private long sze;
private String Name; private String Name;
private String _Directory;
private StreamReader Handle; private StreamReader Handle;
private StreamWriter writeHandle;
} }
} }

View File

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

View File

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

View File

@ -25,7 +25,7 @@ namespace SharedLibrary.Network
var ServerOOBConnection = new UdpClient(); var ServerOOBConnection = new UdpClient();
ServerOOBConnection.Client.SendTimeout = 1000; ServerOOBConnection.Client.SendTimeout = 1000;
ServerOOBConnection.Client.ReceiveTimeout = 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; string QueryString = String.Empty;

View File

@ -26,21 +26,21 @@ namespace SharedLibrary
Players = new List<Player>(new Player[18]); Players = new List<Player>(new Player[18]);
events = new Queue<Event>(); events = new Queue<Event>();
Reports = new List<Report>(); Reports = new List<Report>();
playerHistory = new Queue<PlayerHistory>(); PlayerHistory = new Queue<PlayerHistory>();
ChatHistory = new List<Chat>(); ChatHistory = new List<Chat>();
lastWebChat = DateTime.Now; lastWebChat = DateTime.Now;
nextMessage = 0; nextMessage = 0;
initMacros(); InitializeTokens();
initMessages(); InitializeAutoMessages();
initMaps(); InitializeMaps();
initRules(); InitializeRules();
var commands = mgr.GetCommands(); var commands = mgr.GetCommands();
owner = Manager.GetClientDatabase().GetOwner(); owner = Manager.GetClientDatabase().GetOwner();
if (owner == null) 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 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)); 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)); 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* //Returns current server IP set by `net_ip` -- *STRING*
public String getIP() public String GetIP()
{ {
return IP; return IP;
} }
//Returns current server port set by `net_port` -- *INT* //Returns current server port set by `net_port` -- *INT*
public int getPort() public int GetPort()
{ {
return Port; return Port;
} }
@ -109,7 +98,7 @@ namespace SharedLibrary
/// <param name="Origin">Player to scan for aliases</param> /// <param name="Origin">Player to scan for aliases</param>
abstract public List<Aliases> GetAliases(Player Origin); 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>(); List<int> databaseIDs = new List<int>();
@ -284,36 +273,20 @@ namespace SharedLibrary
await this.ExecuteCommandAsync($"map {newMap.Name}"); 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> /// <summary>
/// Initalize the macro variables /// Initalize the macro variables
/// </summary> /// </summary>
abstract public void initMacros(); abstract public void InitializeTokens();
/// <summary> /// <summary>
/// Read the map configuration /// Read the map configuration
/// </summary> /// </summary>
protected void initMaps() protected void InitializeMaps()
{ {
maps = new List<Map>(); maps = new List<Map>();
IFile mapfile = new IFile("config/maps.cfg"); IFile mapfile = new IFile("config/maps.cfg");
String[] _maps = mapfile.readAll(); String[] _maps = mapfile.ReadAllLines();
mapfile.Close(); mapfile.Close();
if (_maps.Length > 2) // readAll returns minimum one empty string if (_maps.Length > 2) // readAll returns minimum one empty string
{ {
@ -333,13 +306,14 @@ namespace SharedLibrary
/// <summary> /// <summary>
/// Initialize the messages to be broadcasted /// Initialize the messages to be broadcasted
/// todo: this needs to be a serialized file
/// </summary> /// </summary>
protected void initMessages() protected void InitializeAutoMessages()
{ {
messages = new List<String>(); messages = new List<String>();
IFile messageCFG = new IFile("config/messages.cfg"); IFile messageCFG = new IFile("config/messages.cfg");
String[] lines = messageCFG.readAll(); String[] lines = messageCFG.ReadAllLines();
messageCFG.Close(); messageCFG.Close();
if (lines.Length < 2) //readAll returns minimum one empty string if (lines.Length < 2) //readAll returns minimum one empty string
@ -370,13 +344,14 @@ namespace SharedLibrary
/// <summary> /// <summary>
/// Initialize the rules configuration /// Initialize the rules configuration
/// todo: this needs to be a serialized file
/// </summary> /// </summary>
protected void initRules() protected void InitializeRules()
{ {
rules = new List<String>(); rules = new List<String>();
IFile ruleFile = new IFile("config/rules.cfg"); IFile ruleFile = new IFile("config/rules.cfg");
String[] _rules = ruleFile.readAll(); String[] _rules = ruleFile.ReadAllLines();
ruleFile.Close(); ruleFile.Close();
if (_rules.Length > 2) // readAll returns minimum one empty string if (_rules.Length > 2) // readAll returns minimum one empty string
{ {
@ -400,7 +375,7 @@ namespace SharedLibrary
/// <summary> /// <summary>
/// Load up the built in commands /// Load up the built in commands
/// </summary> /// </summary>
abstract public void initCommands(); abstract public void InitializeCommands();
//Objects //Objects
public Interfaces.IManager Manager { get; protected set; } public Interfaces.IManager Manager { get; protected set; }
@ -414,7 +389,7 @@ namespace SharedLibrary
public int totalKills = 0; public int totalKills = 0;
public List<Report> Reports; public List<Report> Reports;
public List<Chat> ChatHistory; public List<Chat> ChatHistory;
public Queue<PlayerHistory> playerHistory { get; private set; } public Queue<PlayerHistory> PlayerHistory { get; private set; }
protected int ConnectionErrors; protected int ConnectionErrors;
protected DateTime LastPoll; protected DateTime LastPoll;

View File

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