Almost finished moving Webfront to a plugin.

This commit is contained in:
RaidMax 2015-08-21 20:11:35 -05:00
parent f4016f6691
commit 7af9c31ea0
26 changed files with 252 additions and 939 deletions

View File

@ -378,13 +378,13 @@ namespace IW4MAdmin
String lookingFor = String.Empty;
foreach(String S in P.getNames())
foreach(String S in P.Names)
{
if (S.Contains(E.Data))
lookingFor = S;
}
Player Current = E.Owner.clientDB.getPlayer(P.getNumber());
Player Current = E.Owner.clientDB.getPlayer(P.Number);
if (Current != null)
{
@ -613,14 +613,13 @@ namespace IW4MAdmin
E.Target.Tell("[^3" + E.Target.Name + "^7]");
StringBuilder message = new StringBuilder();
List<Player> playerAliases = new List<Player>();
E.Owner.getAliases(playerAliases, E.Target);
List<Player> playerAliases = E.Owner.getPlayerAliases(E.Target);
message.Append("Aliases: ");
foreach (Player P in playerAliases)
{
foreach (String S in P.Alias.getNames())
foreach (String S in P.Alias.Names)
{
if (S != String.Empty && S != E.Target.Name)
message.Append(S + " | ");
@ -630,13 +629,13 @@ namespace IW4MAdmin
message = new StringBuilder();
if (E.Target.Alias.getIPS() != null)
if (E.Target.Alias.IPS != null)
{
message.Append("IPs: ");
foreach (Player P2 in playerAliases)
{
foreach (String IP in P2.Alias.getIPS())
foreach (String IP in P2.Alias.IPS)
{
if (IP.Split('.').Length > 3 && IP != String.Empty && !message.ToString().Contains(IP))
message.Append (IP + " | ");

View File

@ -88,10 +88,6 @@
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Reference Include="Kayak">
<HintPath>..\packages\Kayak.0.7.2\lib\Kayak.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="SharedLibary">
<HintPath>..\SharedLibary\SharedLibary\bin\Debug\SharedLibary.dll</HintPath>
<Private>False</Private>
@ -123,7 +119,6 @@
</Compile>
<Compile Include="Server.cs" />
<Compile Include="Utilities.cs" />
<Compile Include="WebFront.cs" />
<Compile Include="IW4_GameStructs.cs" />
</ItemGroup>
<ItemGroup>
@ -146,12 +141,18 @@
<Content Include="plugins\SamplePlugin.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="plugins\Webfront Plugin.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="version.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="webfront\bans.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="webfront\error.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="webfront\footer.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
@ -164,6 +165,9 @@
<Content Include="webfront\main.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="webfront\notfound.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="webfront\player.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
@ -305,7 +309,6 @@ del *.pdb
del *.dll
del app.config
del *.manifest
del *.rm
del *.log
xcopy /E /Y "$(ProjectDir)bin\Release" "$(SolutionDir)Release Build"</PostBuildEvent>
</PropertyGroup>

View File

@ -12,7 +12,6 @@ namespace IW4MAdmin
{
static public double Version { get; private set; }
static private Manager serverManager;
static private IW4MAdmin_Web.WebFront frontEnd;
static void Main(string[] args)
{
@ -43,13 +42,8 @@ namespace IW4MAdmin
}
if (serverManager.getServers() != null)
Program.getManager().mainLog.Write("IW4M Now Initialized! Visit http://127.0.0.1:1624 for server overview.", Log.Level.Production);
Program.getManager().mainLog.Write("IW4M Now Initialized!", Log.Level.Production);
if (serverManager.getServers().Count > 0)
{
frontEnd = new IW4MAdmin_Web.WebFront();
frontEnd.Init();
}
serverMGRThread.Join();
serverManager.mainLog.Write("Shutting down IW4MAdmin...", Log.Level.Debug);
@ -76,8 +70,6 @@ namespace IW4MAdmin
}
Program.getManager().shutDown();
frontEnd.webSchedule.Stop();
frontEnd.webSchedule.Dispose();
return false;
}

View File

@ -9,13 +9,13 @@ namespace IW4MAdmin
public class PluginImporter
{
public static List<Command> potentialCommands;
public static List<EventNotify> potentialNotifies;
public static List<Plugin> potentialNotifies;
public static bool Load()
{
string[] dllFileNames = null;
potentialCommands = new List<Command>();
potentialNotifies = new List<EventNotify>();
potentialNotifies = new List<Plugin>();
if (Directory.Exists(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\plugins"))
dllFileNames = Directory.GetFiles(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + "\\plugins", "*.dll");
@ -47,10 +47,10 @@ namespace IW4MAdmin
Type[] types = Plugin.GetTypes();
foreach(Type assemblyType in types)
{
if(assemblyType.IsClass && assemblyType.BaseType.Name == "EventNotify")
if(assemblyType.IsClass && assemblyType.BaseType.Name == "Notify")
{
Object notifyObject = Activator.CreateInstance(assemblyType);
EventNotify newNotify = (EventNotify)notifyObject;
Plugin newNotify = (Plugin)notifyObject;
potentialNotifies.Add(newNotify);
newNotify.onLoad();
Program.getManager().mainLog.Write("Loaded event plugin \"" + assemblyType.Name + "\"", Log.Level.All);

View File

@ -18,11 +18,39 @@ namespace IW4MAdmin
commandQueue = new Queue<string>();
}
override public void getAliases(List<Player> returnPlayers, Player Origin)
{
if (Origin == null)
return;
private void getAliases(List<Aliases> returnAliases, Aliases currentAlias)
{
foreach(String IP in currentAlias.IPS)
{
List<Aliases> Matching = aliasDB.getPlayer(IP);
foreach(Aliases I in Matching)
{
if (!returnAliases.Contains(I) && returnAliases.Find(x => x.Number == I.Number) == null)
{
returnAliases.Add(I);
getAliases(returnAliases, I);
}
}
}
}
public override List<Aliases> getAliases(Player Origin)
{
List<Aliases> allAliases = new List<Aliases>();
if (Origin == null)
return allAliases;
Aliases currentIdentityAliases = aliasDB.getPlayer(Origin.databaseID);
if (currentIdentityAliases == null)
return allAliases;
getAliases(allAliases, currentIdentityAliases);
return allAliases;
/*
List<Aliases> aliasAliases = new List<Aliases>();
Aliases currentAliases = aliasDB.getPlayer(Origin.databaseID);
@ -56,7 +84,7 @@ namespace IW4MAdmin
}
}
}
}
} */
}
//Add player object p to `players` list
@ -102,16 +130,16 @@ namespace IW4MAdmin
NewPlayer.lastEvent = P.lastEvent;
// lets check aliases
if ((NewPlayer.Alias.getNames().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.Alias.addName(NewPlayer.Name);
NewPlayer.Alias.Names.Add(NewPlayer.Name);
}
// and ips
if (NewPlayer.Alias.getIPS().Find(i => i.Equals(P.IP)) == null || P.IP == null || P.IP == String.Empty)
if (NewPlayer.Alias.IPS.Find(i => i.Equals(P.IP)) == null || P.IP == null || P.IP == String.Empty)
{
NewPlayer.Alias.addIP(P.IP);
NewPlayer.Alias.IPS.Add(P.IP);
}
NewPlayer.updateIP(P.IP);
@ -146,8 +174,7 @@ namespace IW4MAdmin
return true;
}
List<Player> newPlayerAliases = new List<Player>();
getAliases(newPlayerAliases, NewPlayer);
List<Player> newPlayerAliases = getPlayerAliases(NewPlayer);
foreach (Player aP in newPlayerAliases) // lets check their aliases
{
@ -402,7 +429,7 @@ namespace IW4MAdmin
{
Event curEvent = events.Peek();
processEvent(curEvent);
foreach (EventNotify E in PluginImporter.potentialNotifies)
foreach (Notify E in PluginImporter.potentialNotifies)
E.onEvent(curEvent);
events.Dequeue();
}
@ -562,6 +589,7 @@ namespace IW4MAdmin
#endif
}
events.Enqueue(new Event(Event.GType.Stop, "Server monitoring stopped", null, null, this));
isRunning = false;
eventQueueThread.Join();
}
@ -623,6 +651,8 @@ namespace IW4MAdmin
logFile = new IFile(logPath);
Log.Write("Log file is " + logPath, Log.Level.Debug);
Log.Write("Now monitoring " + getName(), Log.Level.Production);
events.Enqueue(new Event(Event.GType.Start, "Server started", null, null, this));
Bans = clientDB.getBans();
return true;
}
catch (Exception E)

View File

@ -1,680 +0,0 @@
#define ENABLED_CRAP_CODE_THAT_NEEDS_TO_BE_REWRITTEN
using System;
using System.Globalization;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Kayak;
using Kayak.Http;
using System.Net;
using SharedLibrary;
using IW4MAdmin;
#if ENABLED_CRAP_CODE_THAT_NEEDS_TO_BE_REWRITTEN
namespace IW4MAdmin_Web
{
class Client
{
public Client ( WebFront.Page req, int cur, IDictionary<String, String> inc, String D, Player P)
{
requestedPage = req;
requestedPageNumber = cur;
requestOrigin = inc;
requestData = D;
playerRequesting = P;
}
public WebFront.Page requestedPage { get; private set; }
public int requestedPageNumber { get; private set; }
public IDictionary<String, String> requestOrigin { get; private set; }
public String requestData { get; private set; }
public Player playerRequesting { get; private set; }
}
class WebFront
{
private Server[] Servers;
public enum Page
{
main,
stats,
bans,
player
}
public WebFront()
{
Servers = Program.getServers();
}
public void Init()
{
webSchedule = KayakScheduler.Factory.Create(new SchedulerDelegate());
webServer = KayakServer.Factory.CreateHttp(new RequestDelegate(), webSchedule);
using (webServer.Listen(new IPEndPoint(IPAddress.Any, 1624)))
{
// runs scheduler on calling thread. this method will block until
// someone calls Stop() on the scheduler.
webSchedule.Start();
}
}
public IScheduler webSchedule;
private IServer webServer;
}
static class Macro
{
static public String parsePagination(int server, int totalItems, int itemsPerPage, int currentPage, String Page)
{
StringBuilder output = new StringBuilder();
output.Append("<div id=pages>");
if ( currentPage > 0)
output.AppendFormat("<a href=/{0}/{1}/?{2}>PREV</a>", server, currentPage - 1, Page);
double totalPages = Math.Ceiling(((float)totalItems / itemsPerPage));
output.Append("<span id=pagination>" + (currentPage + 1) + "/" + totalPages + "</span>");
if ((currentPage + 1) < totalPages)
output.AppendFormat("<a href=/{0}/{1}/?{2}>NEXT</a>", server, currentPage + 1, Page);
output.Append("</div>");
return output.ToString();
}
static public String parseMacros(String input, WebFront.Page Page, int server, int Pagination, bool logged, String Data)
{
StringBuilder buffer = new StringBuilder();
Server[] Servers= Program.getServers();
switch (input)
{
case "SERVERS":
int cycleFix = 0;
for (int i = 0; i < Servers.Count(); i++)
{
if (Program.getServers()[i] == null)
continue;
StringBuilder players = new StringBuilder();
if (Servers[i].getClientNum() < 1)
players.Append("<h2>No Players</h2>");
else
{
int count = 0;
double currentPlayers = Servers[i].statusPlayers.Count;
foreach (Player P in Servers[i].getPlayers())
{
if (P == null)
continue;
if (count % 2 == 0)
{
switch (cycleFix)
{
case 0:
players.Append("<tr class='row-grey'>");
cycleFix = 1;
break;
case 1:
players.Append("<tr class='row-white'>");
cycleFix = 0;
break;
}
}
players.AppendFormat("<td><a href='/{0}/{1}/userip/?player'>{2}</a></td>", i, P.databaseID, SharedLibrary.Utilities.nameHTMLFormatted(P));
if (count % 2 != 0)
{
players.Append("</tr>");
}
count++;
}
}
buffer.AppendFormat(@"<table cellpadding=0 cellspacing=0 class=server>
<tr>
<th class=server_title><span>{0}</span></th>
<th class=server_map><span>{1}</span></th>
<th class=server_players><span>{2}</span></th>
<th class=server_gametype><span>{3}</span></th>
<th><a href=/{4}/0/?stats>Stats</a></th>
<th><a href=/{4}/0/?bans>Bans</a></th>
<th><a class='history' href='/{4}/0/?playerhistory'>History</a></th>
</tr>
</table>
<table cellpadding='0' cellspacing='0' class='players'>
{5}
</table>",
Servers[i].getName(), Servers[i].getMap(), Servers[i].getClientNum() + "/" + Servers[i].getMaxClients(), SharedLibrary.Utilities.gametypeLocalized(Servers[i].getGametype()), i, players.ToString());
buffer.AppendFormat("<div class='chatHistory' id='chatHistory_{0}'></div><script type='text/javascript'>$( document ).ready(function() {{ setInterval({1}loadChatMessages({0}, '#chatHistory_{0}'){1}, 2500); }});</script><div class='null' style='clear:both;'></div>", i, '\"');
if (Servers[i].getClientNum() > 0)
buffer.AppendFormat("<form class='chatOutFormat' action={1}javascript:chatRequest({0}, 'chatEntry_{0}'){1}><input class='chatFormat_text' type='text' placeholder='Enter a message...' id='chatEntry_{0}'/><input class='chatFormat_submit' type='submit'/></form>", i, '\"');
buffer.Append("<hr/>");
}
return buffer.ToString();
case "TITLE":
return "IW4M Administration";
case "BANS":
buffer.Append("<table cellspacing=0 class=bans>");
int totalBans = Program.getServers()[0].Bans.Count;
int range;
int start = Pagination*30;
cycleFix = 0;
if (totalBans <= 30)
range = totalBans - 1;
else if ((totalBans - start) < 30)
range = (totalBans - start);
else
range = 30;
List<Ban> Bans = new List<Ban>();
if (totalBans > 0)
Bans = Program.getServers()[0].Bans.GetRange(start, range).OrderByDescending(x => x.When).ToList();
else
Bans.Add(new Ban("No Bans", "0", "0", DateTime.Now, ""));
buffer.Append("<h1 style=margin-top: 0;>{{TIME}}</h1><hr /><tr><th>Name</th><th style=text-align:left;>Offense</th><th style=text-align:left;>Banned By</th><th style='width: 175px; text-align:right;padding-right: 80px;'>Time</th></tr>");
if (Bans[0] != null)
buffer = buffer.Replace("{{TIME}}", "From " + SharedLibrary.Utilities.timePassed(Bans[0].When) + " ago" + " &mdash; " + totalBans + " total");
for (int i = 0; i < Bans.Count; i++)
{
if (Bans[i] == null)
continue;
Player P = Program.getServers()[0].clientDB.getPlayer(Bans[i].npID, -1);
Player B = Program.getServers()[0].clientDB.getPlayer(Bans[i].bannedByID, -1);
if (P == null)
P = new Player("Unknown", "n/a", 0, 0, 0, "Unknown", 0, "");
if (B == null)
B = new Player("Unknown", "n/a", 0, 0, 0, "Unknown", 0, "");
if (P.lastOffense == String.Empty)
P.lastOffense = "Evade";
if (P != null && B != null)
{
if (B.npID == P.npID)
B.updateName("IW4MAdmin"); // shh it will all be over soon
String Prefix;
if (cycleFix % 2 == 0)
Prefix = "class=row-grey";
else
Prefix = "class=row-white";
String Link = "/" + server + "/" + P.databaseID + "/userip/?player";
buffer.AppendFormat("<tr {4}><td><a href='{5}'>{0}</a></th><td style='border-left: 3px solid #bbb; text-align:left;'>{1}</td><td style='border-left: 3px solid #bbb;text-align:left;'>{2}</td><td style='width: 175px; text-align:right;'>{3}</td></tr></div>", P.Name, P.lastOffense, SharedLibrary.Utilities.nameHTMLFormatted(B), Bans[i].getWhen(), Prefix, Link);
cycleFix++;
}
}
buffer.Append("</table><hr/>");
buffer.Append(parsePagination(server, Servers[0].Bans.Count, 30, Pagination, "bans"));
return buffer.ToString();
case "PAGE":
buffer.Append("<div id=pages>");
return buffer.ToString();
case "STATS":
int totalStats = 0;
buffer.Append("<h1 style='margin-top: 0;'>Starting at #{{TOP}}</h1><hr />");
buffer.Append("<table style='width:100%' cellspacing=0 class=stats>");
start = Pagination*30;
if (totalStats <= 30)
range = totalStats - 1;
else if ((totalStats - start) < 30 )
range = (totalStats - start);
else
range = 30;
//List<Stats> Stats = Servers[server].statDB.getMultipleStats(start, range).OrderByDescending(x => x.Skill).ToList();
buffer.Append("<tr><th style=text-align:left;>Name</th><th style=text-align:left;>Kills</th><th style=text-align:left;>Deaths</th><th style=text-align:left;>KDR</th><th style='width: 175px; text-align:right;'>Rating</th></tr>");
cycleFix = 0;
/*for (int i = 0; i < totalStats; i++)
{
if (i >= Stats.Count -1 || Stats[i] == null )
continue;
Player P = Servers[server].clientDB.getPlayer(Stats[i].statIndex);
if (P == null)
continue;
P.stats = Stats[i];
if (P.stats != null)
{
String Prefix;
if (cycleFix % 2 == 0)
Prefix = "class=row-grey";
else
Prefix = "class=row-white";
String Link = "/" + server + "/" + P.databaseID + "/userip/?player";
buffer.AppendFormat("<tr {5}><td><a href='{6}'>{0}</a></td><td style='border-left: 3px solid #bbb; text-align:left;'>{1}</td><td style='border-left: 3px solid #bbb;text-align:left;'>{2}</td><td style='border-left: 3px solid #bbb;text-align:left;'>{3}</td><td style='width: 175px; text-align:right;'>{4}</td></tr></div>", P.Name, P.stats.Kills, P.stats.Deaths, P.stats.KDR, P.stats.Skill, Prefix, Link);
cycleFix++;
}
}*/
buffer.Append("</table><hr/>");
buffer.Append(parsePagination(server, totalStats, 30, Pagination, "stats"));
return buffer.ToString().Replace("{{TOP}}", (start + 1).ToString());
case "PLAYER":
buffer.Append("<table class='player_info'><tr><th>Name</th><th>Aliases</th><th>IP</th><th>Rating</th><th>Level</th><th>Connections</th><th>Last Seen</th><th>Profile</th>");
List<Player> matchingPlayers = new List<Player>();
if (Data == null)
matchingPlayers.Add(Servers[server].clientDB.getPlayer(Pagination));
else
{
var alias = Servers[server].aliasDB.findPlayers(Data);
foreach (var a in alias)
{
var p = Servers[server].clientDB.getPlayer(a.getNumber());
if (p != null)
{
List<Player> aliases = new List<Player>();
Servers[server].getAliases(aliases, p);
foreach (var pa in aliases)
{
if (!matchingPlayers.Exists(x => x.databaseID == pa.databaseID))
matchingPlayers.Add(pa);
}
}
}
}
if (matchingPlayers == null)
buffer.Append("</table>");
else
{
foreach (Player Player in matchingPlayers)
{
if (Player == null)
continue;
buffer.Append("<tr>");
StringBuilder str = new StringBuilder();
List<Player> aliases = new List<Player>();
Servers[server].getAliases(aliases, Player);
foreach (Player a in aliases)
{
if (Data != null)
{
if (a.Alias.getNames().Exists(p => p.ToLower().Contains(Data.ToLower())) && a.databaseID != Player.databaseID)
{
str.AppendFormat("<span>{0}</span><br/>", a.Name);
break;
}
}
else
str.AppendFormat("<span>{0}</span><br/>", a.Name);
}
StringBuilder IPs = new StringBuilder();
if (logged)
{
foreach (Player a in aliases)
{
foreach (String ip in a.Alias.getIPS())
{
if (!IPs.ToString().Contains(ip))
IPs.AppendFormat("<span>{0}</span><br/>", ip);
}
}
}
else
IPs.Append("XXX.XXX.XXX.XXX");
Int64 forumID = 0;
if (Player.npID.Length == 16)
{
forumID = Int64.Parse(Player.npID.Substring(0, 16), NumberStyles.AllowHexSpecifier);
forumID = forumID - 76561197960265728;
}
String Screenshot = String.Empty;
if (logged)
Screenshot = String.Format("<a href='http://server.nbsclan.org/screen.php?id={0}&name={1}'><div style='background-image:url(http://server.nbsclan.org/shutter.png); width: 20px; height: 20px;float: right; position:relative; right: 21%; background-size: contain;'></div></a>", forumID, Player.Name);
buffer.AppendFormat("<td><a style='float: left;' href='{9}'>{0}</a>{10}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6} ago</td><td><a href='https://repziw4.de/memberlist.php?mode=viewprofile&u={7}'>{8}</a></td>", Player.Name, str, IPs, 0, SharedLibrary.Utilities.nameHTMLFormatted(Player), Player.Connections, Player.getLastConnection(), forumID, Player.Name, "/0/" + Player.databaseID + "/userip/?player", Screenshot);
buffer.Append("</tr>");
}
buffer.Append("</table>");
}
return buffer.ToString();
default:
return input;
}
}
static public String findMacros(String input, Client C, int server)
{
String output = input;
bool logged = Program.getServers()[server].clientDB.getAdmins().Exists(player => player.IP == C.requestOrigin["Host"].Split(':')[0]);
switch (C.requestedPage)
{
case WebFront.Page.main:
output = output.Replace("{{SERVERS}}", parseMacros("SERVERS", C.requestedPage, server, C.requestedPageNumber, logged, C.requestData));
break;
case WebFront.Page.bans:
output = output.Replace("{{BANS}}", parseMacros("BANS", C.requestedPage, server, C.requestedPageNumber, logged, C.requestData));
break;
case WebFront.Page.stats:
output = output.Replace("{{STATS}}", parseMacros("STATS", C.requestedPage, server, C.requestedPageNumber, logged, C.requestData));
break;
case WebFront.Page.player:
output = output.Replace("{{PLAYER}}", parseMacros("PLAYER", C.requestedPage, server, C.requestedPageNumber, (C.playerRequesting.Level > Player.Permission.Flagged), C.requestData));
break;
}
output = output.Replace("{{TITLE}}", "IW4M Administration");
output = output.Replace("{{VERSION}}", Program.Version.ToString());
return output;
}
}
class SchedulerDelegate : ISchedulerDelegate
{
public void OnException(IScheduler scheduler, Exception e)
{
//Program.getManager().mainLog.Write(e.InnerException.Message);
//Console.Write(e.InnerException);
// e.DebugStackTrace();
Program.getManager().mainLog.Write("Web front encountered an error!");
}
public void OnStop(IScheduler scheduler)
{
}
}
class RequestDelegate : IHttpRequestDelegate
{
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response)
{
String type = "text/html";
if (request.Uri.StartsWith("/"))
{
//Program.getManager().mainLog.Write("[WEBFRONT] Processing Request for " + request.Uri);
var body = String.Empty;
if (request.Uri.StartsWith("/"))
{
IFile Header = new IFile("webfront\\header.html");
var header = Header.getLines();
Header.Close();
IFile Footer = new IFile("webfront\\footer.html");
var footer = Footer.getLines();
Footer.Close();
String[] req = request.Path.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
int server = 0;
int page = 0;
if (req.Length > 1)
{
Int32.TryParse(req[0], out server);
Int32.TryParse(req[1], out page);
}
if (Program.getServers().Length < 1)
{
body = "<h1 style='font-family: Segoe UI;'>IT SEEMS LIKE THERE ARE NO LONGER ANY SERVERS BEING MONITORED!</h1>";
}
else if (request.QueryString == "bans")
{
IFile Bans = new IFile("webfront\\bans.html");
var bans = Bans.getLines();
Bans.Close();
Client toSend = new Client(WebFront.Page.bans, page, request.Headers, null, null);
body = Macro.findMacros((header + bans + footer), toSend, server);
}
else if (request.QueryString == "stats")
{
IFile Stats = new IFile("webfront\\stats.html");
var stats = Stats.getLines();
Stats.Close();
Client toSend = new Client(WebFront.Page.stats, page, request.Headers, null, null);
body = Macro.findMacros(header + stats + footer, toSend, server);
}
else if (request.QueryString == "playerhistory")
{
//type = "text/plain";
if (Program.getServers().Length < server)
return;
StringBuilder test = new StringBuilder();
test.Append("<script type='text/javascript' src='//www.google.com/jsapi'></script><div id='chart_div'></div>");
test.Append("<script> var players = [");
int count = 1;
IW4MServer castServer = (IW4MServer)Program.getServers()[server];
List<pHistory> run = castServer.playerHistory.ToList();
foreach (pHistory i in run) //need to reverse for proper timeline
{
test.AppendFormat("[new Date({0}, {1}, {2}, {3}, {4}), {5}]", i.When.Year, i.When.Month - 1, i.When.Day, i.When.Hour, i.When.Minute, i.Players);
if (count < run.Count)
test.Append(",\n");
count++;
}
test.Append("];\n");
test.Append("</script>");
IFile Graph = new IFile("webfront\\graph.html");
var graph = Graph.getLines();
Graph.Close();
body = test.ToString() + graph ;
}
else if (request.QueryString == "player")
{
IFile Player = new IFile("webfront\\player.html");
var player = Player.getLines();
Player.Close();
String Data = null, IP = null, ID = null;
if (req.Length > 3)
{
ID = req[1];
IP = req[2];
Data = req[3];
}
else if (req.Length >2)
{
ID = req[1];
IP = req[2];
}
if (Program.getServers().Length < server)
return;
Player P = Program.getServers()[server].clientDB.getPlayer(IP);
if (P == null)
P = new Player("Guest", "Guest", 0, 0);
Client toSend = new Client(WebFront.Page.player, page, request.Headers, Data, P);
body = Macro.findMacros(header + player + footer, toSend, server);
}
else if (request.QueryString == "chat")
{
StringBuilder chatMessages = new StringBuilder();
#if DEBUG
// if (Program.Servers[server].chatHistory.Count < 8)
// Program.Servers[server].chatHistory.Add(new Chat(new Player("TEST", "xuid", 0, 0), "TEST MESSAGE", DateTime.Now));
#endif
if (Program.getServers().Length < server)
return;
String IP, Text;
if (req.Length > 3)
{
IP = req[2];
Text = SharedLibrary.Utilities.cleanChars(HttpUtility.UrlDecode(req[3]));
}
else
{
IP = null;
Text = null;
}
if (IP == null && Program.getServers()[server].getClientNum() > 0)
{
chatMessages.Append("<table id='table_chatHistory'>");
foreach (Chat Message in Program.getServers()[server].chatHistory)
chatMessages.AppendFormat("<tr><td class='chat_name' style='text-align: left;'>{0}</td><td class='chat_message'>{1}</td><td class='chat_time' style='text-align: right;'>{2}</td></tr>", SharedLibrary.Utilities.nameHTMLFormatted(Message.Origin), Message.Message, Message.timeString());
chatMessages.Append("</table>");
body = chatMessages.ToString();
}
else if (Text != null && Text.Length > 4)
{
Player requestPlayer = Program.getServers()[server].clientDB.getPlayer(IP);
if (requestPlayer != null)
Program.getServers()[server].webChat(requestPlayer, Text);
}
}
else if (request.QueryString == "pubbans")
{
type = "text/plain";
StringBuilder banTXT = new StringBuilder();
banTXT.AppendFormat("===========================================\nIW4M ADMIN PUBLIC BAN LIST\nGENERATED {0}\nIP---GUID---REASON---TIME\n===========================================\n", DateTime.Now.ToString());
foreach (Ban B in Program.getServers()[0].Bans)
{
if (B.IP != null && B.IP != String.Empty && B.Reason != null && B.Reason != String.Empty)
banTXT.AppendFormat("{0}---{1}---{2}---{3}\n", B.IP, B.npID, B.Reason.Trim(), Math.Round((B.When-DateTime.MinValue).TotalSeconds, 0));
}
body = banTXT.ToString();
}
else
{
IFile Main = new IFile("webfront\\main.html");
var main = Main.getLines();
Main.Close();
Client toSend = new Client(WebFront.Page.main, page, request.Headers, null, null);
body = Macro.findMacros(header + main + footer, toSend, server);
}
//Program.getServers()[server].Log.Write("Webfront processed request for " + request.Uri, Log.Level.Debug);
}
var headers = new HttpResponseHead()
{
Status = "200 OK",
Headers = new Dictionary<string, string>()
{
{ "Content-Type", type },
{ "Content-Length", body.Length.ToString() },
}
};
response.OnResponse(headers, new BufferedProducer(body));
}
else
{
var responseBody = "The resource you requested ('" + request.Uri + "') could not be found.";
var headers = new HttpResponseHead()
{
Status = "404 Not Found",
Headers = new Dictionary<string, string>()
{
{ "Content-Type", type },
{ "Content-Length", responseBody.Length.ToString() }
}
};
var body = new BufferedProducer(responseBody);
response.OnResponse(headers, body);
}
}
class BufferedProducer : IDataProducer
{
ArraySegment<byte> data;
public BufferedProducer(string data) : this(data, Encoding.UTF8) { }
public BufferedProducer(string data, Encoding encoding) : this(encoding.GetBytes(data)) { }
public BufferedProducer(byte[] data) : this(new ArraySegment<byte>(data)) { }
public BufferedProducer(ArraySegment<byte> data)
{
this.data = data;
}
public IDisposable Connect(IDataConsumer channel)
{
// null continuation, consumer must swallow the data immediately.
channel.OnData(data, null);
channel.OnEnd();
return null;
}
}
class BufferedConsumer : IDataConsumer
{
List<ArraySegment<byte>> buffer = new List<ArraySegment<byte>>();
Action<string> resultCallback;
Action<Exception> errorCallback;
public BufferedConsumer(Action<string> resultCallback, Action<Exception> errorCallback)
{
this.resultCallback = resultCallback;
this.errorCallback = errorCallback;
}
public bool OnData(ArraySegment<byte> data, Action continuation)
{
// since we're just buffering, ignore the continuation.
buffer.Add(data);
return false;
}
public void OnError(Exception error)
{
errorCallback(error);
}
public void OnEnd()
{
// turn the buffer into a string.
var str = buffer
.Select(b => Encoding.UTF8.GetString(b.Array, b.Offset, b.Count))
.Aggregate((result, next) => result + next);
resultCallback(str);
}
}
}
}
#endif

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,5 +1,5 @@
<div id="container">
<div class="h0" style="margin-top: 0; line-height:normal;">BANS<br/><a style="padding: 0; margin: 0; font-size: 24px; float: right;" href="/">Back</a></div>
<div id="logo_shit"></div>
{{BANS}}
<div class="h0" style="margin-top: 0; line-height:normal;">BANS<br/><a style="padding: 0; margin: 0; font-size: 24px; float: right;" href="/">Back</a></div>
<div id="logo_shit"></div>
{{BANS}}
</div>

11
Admin/webfront/error.html Normal file
View File

@ -0,0 +1,11 @@
<div id="container">
<div class="h0" style="margin-top: 0; line-height:normal;">ERROR!<br /><a style="padding: 0; margin: 0; font-size: 24px; float: right;" href="/">Back</a></div>
<div id="logo_shit"></div>
<div style="clear:both"></div>
<hr />
<div style="font-size: 16pt; text-align:center">
<br />
Uh Oh, it looks like there was an error processing your request. <br />
Reason: <span style="color: red;">{{ERROR}}</span>
</div>
</div>

View File

@ -394,7 +394,7 @@
<body>
<script type="text/javascript">
function loadChatMessages(server, divElem) {
$(divElem).load("/" + server + "/0/?chat");
$(divElem).load("/chat?server=" + server);
}
</script>
<script type="text/javascript">
@ -402,7 +402,7 @@
var Message = document.getElementById(divElem).value.replace(/\s/g, "%20").replace(/[\\|\/]/g,"");
if (Message.length > 4 && Message.length < 51)
{
$(".null").load("/" + server + "/0/" + userip + "/" + Message + "/?chat");
$(".null").load("/chat?server=" + server);
$("#" + divElem).val('');
}
else if (Message.length <= 4)
@ -415,7 +415,7 @@
function searchPlayerName() {
var nameValue = document.getElementById("search_playerName").value;
if (nameValue.length > 0)
window.location.href = ("/0/0/" + userip + "/" + nameValue + "/?player");
window.location.href = ("/player?query=" + encodeURIComponent(nameValue));
}
</script>
<div id="player_search">

View File

@ -0,0 +1,5 @@
<div id="container">
<div class="h0" style="margin-top: 0">IW4M Admin</div><div id="logo_shit"></div>
<h1 style="margin-top: 0; text-align:center">404 Page not found!</h1>
<hr />
</div>

View File

@ -4,4 +4,4 @@
<div style="clear:both"></div>
<hr/>
{{PLAYER}}
</div>
</div>

View File

@ -6,6 +6,7 @@ MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IW4M ADMIN", "Admin\IW4M ADMIN.csproj", "{DD5DCDA2-51DB-4B1A-922F-5705546E6115}"
ProjectSection(ProjectDependencies) = postProject
{4785AB75-66F3-4391-985D-63A5A049A0FA} = {4785AB75-66F3-4391-985D-63A5A049A0FA}
{99E36EBD-1FA1-494C-8A66-BECE64EFF378} = {99E36EBD-1FA1-494C-8A66-BECE64EFF378}
{D51EECEB-438A-47DA-870F-7D7B41BC24D6} = {D51EECEB-438A-47DA-870F-7D7B41BC24D6}
EndProjectSection
EndProject
@ -16,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SamplePlugin", "SamplePlugi
{D51EECEB-438A-47DA-870F-7D7B41BC24D6} = {D51EECEB-438A-47DA-870F-7D7B41BC24D6}
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Webfront Plugin", "Webfront Plugin\Webfront Plugin.csproj", "{99E36EBD-1FA1-494C-8A66-BECE64EFF378}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -34,6 +37,10 @@ Global
{4785AB75-66F3-4391-985D-63A5A049A0FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4785AB75-66F3-4391-985D-63A5A049A0FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4785AB75-66F3-4391-985D-63A5A049A0FA}.Release|Any CPU.Build.0 = Release|Any CPU
{99E36EBD-1FA1-494C-8A66-BECE64EFF378}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{99E36EBD-1FA1-494C-8A66-BECE64EFF378}.Debug|Any CPU.Build.0 = Debug|Any CPU
{99E36EBD-1FA1-494C-8A66-BECE64EFF378}.Release|Any CPU.ActiveCfg = Release|Any CPU
{99E36EBD-1FA1-494C-8A66-BECE64EFF378}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Binary file not shown.

Binary file not shown.

View File

@ -65,7 +65,7 @@ namespace SamplePlugin
}
#endif
public class StatCommand: Command
public class StatCommand : Command
{
public StatCommand() : base("stats", "view your stats. syntax !stats", "xlrstats", Player.Permission.User, 0, false) { }
@ -77,13 +77,12 @@ namespace SamplePlugin
}
}
public class Stats : EventNotify
public class Stats : Notify
{
public static StatsDB playerStats { get; private set; }
public override void onEvent(Event E)
{
Console.WriteLine("event type is " + E.Type);
if (E.Type == Event.GType.Kill)
{
Player Killer = E.Origin;

View File

@ -107,6 +107,7 @@ namespace SharedLibrary
protected DataTable GetDataTable(String sql)
{
DataTable dt = new DataTable();
try
{
waitForClose();
@ -170,24 +171,60 @@ namespace SharedLibrary
if (Result != null && Result.Rows.Count > 0)
{
DataRow ResponseRow = Result.Rows[0];
DateTime LC;
DateTime lastCon = DateTime.MinValue;
DateTime.TryParse(ResponseRow["LastConnection"].ToString(), out lastCon);
try
{
LC = DateTime.Parse(ResponseRow["LastConnection"].ToString());
}
catch (Exception)
{
LC = DateTime.Now;
}
return new Player(ResponseRow["Name"].ToString(), ResponseRow["npID"].ToString(), cNum, (Player.Permission)(ResponseRow["Level"]), Convert.ToInt32(ResponseRow["Number"]), ResponseRow["LastOffense"].ToString(), (int)ResponseRow["Connections"], ResponseRow["IP"].ToString(), LC);
return new Player(ResponseRow["Name"].ToString(), ResponseRow["npID"].ToString(), cNum, (Player.Permission)(ResponseRow["Level"]), Convert.ToInt32(ResponseRow["Number"]), ResponseRow["LastOffense"].ToString(), (int)ResponseRow["Connections"], ResponseRow["IP"].ToString(), lastCon);
}
else
return null;
}
public List<Player> getPlayers(List<String> npIDs)
{
List<Player> returnssss = new List<Player>();
String test = String.Join("' OR npID = '", npIDs);
String Query = String.Format("SELECT * FROM CLIENTS WHERE npID = '{0}'", test);
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
{
foreach (DataRow ResponseRow in Result.Rows)
{
DateTime lastCon = DateTime.MinValue;
DateTime.TryParse(ResponseRow["LastConnection"].ToString(), out lastCon);
returnssss.Add(new Player(ResponseRow["Name"].ToString(), ResponseRow["npID"].ToString(), -1, (Player.Permission)(ResponseRow["Level"]), Convert.ToInt32(ResponseRow["Number"]), ResponseRow["LastOffense"].ToString(), (int)ResponseRow["Connections"], ResponseRow["IP"].ToString(), lastCon));
}
}
return returnssss;
}
public List<Player> getPlayers(List<int> databaseIDs)
{
List<Player> returnssss = new List<Player>();
String test = String.Join("' OR Number = '", databaseIDs);
String Query = String.Format("SELECT * FROM CLIENTS WHERE Number = '{0}'", test);
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
{
foreach (DataRow ResponseRow in Result.Rows)
{
DateTime lastCon = DateTime.MinValue;
DateTime.TryParse(ResponseRow["LastConnection"].ToString(), out lastCon);
returnssss.Add(new Player(ResponseRow["Name"].ToString(), ResponseRow["npID"].ToString(), -1, (Player.Permission)(ResponseRow["Level"]), Convert.ToInt32(ResponseRow["Number"]), ResponseRow["LastOffense"].ToString(), (int)ResponseRow["Connections"], ResponseRow["IP"].ToString(), lastCon));
}
}
return returnssss;
}
//Overloaded method for getPlayer, returns Client with matching DBIndex, null if none found
public Player getPlayer(int dbIndex)
{
@ -204,7 +241,7 @@ namespace SharedLibrary
}
catch (Exception)
{
LC = DateTime.Now;
LC = DateTime.MinValue;
}
return new Player(p["Name"].ToString(), p["npID"].ToString(), -1, (Player.Permission)(p["Level"]), Convert.ToInt32(p["Number"]), p["LastOffense"].ToString(), Convert.ToInt32(p["Connections"]), p["IP"].ToString(), LC);
@ -217,7 +254,7 @@ namespace SharedLibrary
//get player by ip, (used for webfront)
public Player getPlayer(String IP)
{
String Query = String.Format("SELECT * FROM CLIENTS WHERE IP='{0}'", IP);
String Query = String.Format("SELECT * FROM CLIENTS WHERE IP = '{0}'", IP);
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
@ -255,7 +292,7 @@ namespace SharedLibrary
//Returns a list of players matching name parameter, null if no players found matching
public List<Player> findPlayers(String name)
{
String Query = String.Format("SELECT * FROM CLIENTS WHERE Name LIKE '%{0}%' LIMIT 8", name);
String Query = String.Format("SELECT * FROM CLIENTS WHERE Name LIKE '%{0}%' LIMIT 32", name);
DataTable Result = GetDataTable(Query);
List<Player> Players = new List<Player>();
@ -271,7 +308,7 @@ namespace SharedLibrary
}
catch (Exception)
{
LC = DateTime.Now;
LC = DateTime.MinValue;
}
Players.Add(new Player(p["Name"].ToString(), p["npID"].ToString(), -1, (Player.Permission)(p["Level"]), Convert.ToInt32(p["Number"]), p["LastOffense"].ToString(), Convert.ToInt32(p["Connections"]), p["IP"].ToString(), LC));
@ -403,144 +440,6 @@ namespace SharedLibrary
}
}
/*public class StatsDB : Database
{
public StatsDB(String FN) : base(FN) { }
public override void Init()
{
if (!File.Exists(FileName))
{
String Create = "CREATE TABLE [STATS] ( [Number] INTEGER, [KILLS] INTEGER DEFAULT 0, [DEATHS] INTEGER DEFAULT 0, [KDR] REAL DEFAULT 0, [SKILL] REAL DEFAULT 0, [MEAN] REAL DEFAULT 0, [DEV] REAL DEFAULT 0 );";
ExecuteNonQuery(Create);
}
}
// Return stats for player specified by Database ID, null if no matches
public Stats getStats(int DBID)
{
String Query = String.Format("SELECT * FROM STATS WHERE Number = '{0}'", DBID);
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
{
DataRow ResponseRow = Result.Rows[0];
if (ResponseRow["MEAN"] == DBNull.Value)
ResponseRow["MEAN"] = 0; // Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.Mean;
if (ResponseRow["DEV"] == DBNull.Value)
ResponseRow["DEV"] = 0; // Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.StandardDeviation;
if (ResponseRow["SKILL"] == DBNull.Value)
ResponseRow["SKILL"] = 0;
return new Stats(Convert.ToInt32(ResponseRow["Number"]), Convert.ToInt32(ResponseRow["KILLS"]), Convert.ToInt32(ResponseRow["DEATHS"]), Convert.ToDouble(ResponseRow["KDR"]), Convert.ToDouble(ResponseRow["SKILL"]), Convert.ToDouble(ResponseRow["MEAN"]), Convert.ToDouble(ResponseRow["DEV"]));
}
else
return null;
}
public void addPlayer(Player P)
{
Dictionary<String, object> newPlayer = new Dictionary<String, object>();
newPlayer.Add("Number", P.databaseID);
newPlayer.Add("KILLS", 0);
newPlayer.Add("DEATHS", 0);
newPlayer.Add("KDR", 0);
newPlayer.Add("SKILL", 0); //Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.ConservativeRating);
newPlayer.Add("MEAN", 0); //Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.Mean);
newPlayer.Add("DEV", 0); //Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.StandardDeviation);
Insert("STATS", newPlayer);
}
//Update stat information of specified player
public void updatePlayer(Player P)
{
if (P.stats == null)
return;
Dictionary<String, object> updatedPlayer = new Dictionary<String, object>();
updatedPlayer.Add("KILLS", P.stats.Kills);
updatedPlayer.Add("DEATHS", P.stats.Deaths);
updatedPlayer.Add("KDR", Math.Round(P.stats.KDR, 2));
updatedPlayer.Add("SKILL", P.stats.Skill);
//updatedPlayer.Add("MEAN", P.stats.Rating.Mean);
//updatedPlayer.Add("DEV", P.stats.Rating.StandardDeviation);
Update("STATS", updatedPlayer, String.Format("Number = '{0}'", P.databaseID));
}
//Returns top 5 players (we filter through them later)
public List<Stats> topStats()
{
String Query = String.Format("SELECT * FROM STATS WHERE KILLS > '{0}' AND KDR < '{1}' AND SKILL > '{2}' ORDER BY SKILL DESC LIMIT 5", 250, 7, 245);
DataTable Result = GetDataTable(Query);
List<Stats> Top = new List<Stats>();
if (Result != null && Result.Rows.Count > 0)
{
foreach (DataRow D in Result.Rows)
{
if (D["MEAN"] == DBNull.Value || D["DEV"] == DBNull.Value || D["SKILL"] == DBNull.Value)
continue;
Stats S = new Stats(Convert.ToInt32(D["Number"]), Convert.ToInt32(D["KILLS"]), Convert.ToInt32(D["DEATHS"]), Convert.ToDouble(D["KDR"]), Convert.ToDouble(D["SKILL"]), Convert.ToDouble(D["MEAN"]), Convert.ToDouble(D["DEV"]));
Top.Add(S);
}
}
return Top;
}
public List<Stats> getMultipleStats(int start, int length)
{
String Query = String.Format("SELECT * FROM STATS ORDER BY SKILL DESC LIMIT '{0}' OFFSET '{1}'", length, start);
DataTable Result = GetDataTable(Query);
List<Stats> Stats = new List<Stats>();
if (Result != null && Result.Rows.Count > 0)
{
foreach (DataRow D in Result.Rows)
{
if (D["MEAN"] == DBNull.Value)
continue;
if (D["DEV"] == DBNull.Value)
continue;
if (D["SKILL"] == DBNull.Value)
D["SKILL"] = 0;
Stats S = new Stats(Convert.ToInt32(D["Number"]), Convert.ToInt32(D["KILLS"]), Convert.ToInt32(D["DEATHS"]), Convert.ToDouble(D["KDR"]), Convert.ToDouble(D["SKILL"]), Convert.ToDouble(D["MEAN"]), Convert.ToDouble(D["DEV"]));
Stats.Add(S);
}
}
return Stats;
}
public int totalStats()
{
DataTable Result = GetDataTable("SELECT * FROM STATS");
return Result.Rows.Count;
}
public void clearSkill()
{
String Query = "SELECT * FROM STATS";
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
{
foreach (DataRow D in Result.Rows)
Update("STATS", new Dictionary<String, Object>() { { "SKILL", 1 } }, String.Format("Number = '{0}'", D["Number"]));
}
}
}*/
public class AliasesDB : Database
{
public AliasesDB(String FN) : base(FN) { }
@ -609,9 +508,9 @@ namespace SharedLibrary
{
Dictionary<String, object> newPlayer = new Dictionary<String, object>();
newPlayer.Add("Number", Alias.getNumber());
newPlayer.Add("NAMES", Alias.getNamesDB());
newPlayer.Add("IPS", Alias.getIPSDB());
newPlayer.Add("Number", Alias.Number);
newPlayer.Add("NAMES", String.Join(";", Alias.Names));
newPlayer.Add("IPS", String.Join(";", Alias.IPS));
Insert("ALIASES", newPlayer);
}
@ -620,11 +519,11 @@ namespace SharedLibrary
{
Dictionary<String, object> updatedPlayer = new Dictionary<String, object>();
updatedPlayer.Add("Number", Alias.getNumber());
updatedPlayer.Add("NAMES", Alias.getNamesDB());
updatedPlayer.Add("IPS", Alias.getIPSDB());
updatedPlayer.Add("Number", Alias.Number);
updatedPlayer.Add("NAMES", String.Join(";", Alias.Names));
updatedPlayer.Add("IPS", String.Join(";", Alias.IPS));
Update("ALIASES", updatedPlayer, String.Format("Number = '{0}'", Alias.getNumber()));
Update("ALIASES", updatedPlayer, String.Format("Number = '{0}'", Alias.Number));
}
}
}

View File

@ -29,6 +29,8 @@ namespace SharedLibrary
public enum GType
{
//FROM SERVER
Start,
Stop,
Connect,
Disconnect,
Say,
@ -126,10 +128,4 @@ namespace SharedLibrary
public Player Target;
public Server Owner;
}
public abstract class EventNotify
{
public abstract void onEvent(Event E);
public abstract void onLoad();
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace SharedLibrary
{
@ -9,50 +10,13 @@ namespace SharedLibrary
public Aliases(int Num, String N, String I)
{
Number = Num;
Names = N;
IPS = I;
Names = N.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
IPS = new List<String>(I.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
public List<String> getNames()
{
return new List<String>(Names.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
public List<String> getIPS()
{
return new List<String>(IPS.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
public String getIPSDB()
{
return IPS;
}
public String getNamesDB()
{
return Names;
}
public int getNumber()
{
return Number;
}
public void addName(String Name)
{
if (Name.Trim() != String.Empty && Name != null)
Names += ';' + Name;
}
public void addIP(String IP)
{
if (IP.Trim() != String.Empty && IP != null)
IPS += ';' + IP;
}
private String Names;
private String IPS;
private int Number;
public List<String> Names { get; private set; }
public List<String> IPS { get; private set; }
public int Number { get; private set; }
}
public class Player
@ -80,7 +44,6 @@ namespace SharedLibrary
IP = "";
Warnings = 0;
Alias = new Aliases(0, "", "");
//stats = new Stats(0, 0, 0, 0, Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.ConservativeRating, Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.Mean, Moserware.Skills.GameInfo.DefaultGameInfo.DefaultRating.StandardDeviation);
LastConnection = DateTime.Now;
}

17
SharedLibary/Plugin.cs Normal file
View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharedLibrary
{
public abstract class Plugin
{
public abstract void onLoad();
}
public abstract class Notify : Plugin
{
public abstract void onEvent(Event E);
}
}

View File

@ -23,6 +23,7 @@ namespace SharedLibrary
clientDB = new ClientsDB("clients.rm");
aliasDB = new AliasesDB("aliases.rm");
Bans = new List<Ban>();
players = new List<Player>(new Player[18]);
events = new Queue<Event>();
Macros = new Dictionary<String, Object>();
@ -108,9 +109,18 @@ namespace SharedLibrary
/// <summary>
/// Get any know aliases ( name or ip based ) from the database
/// </summary>
/// <param name="returnPlayers">List of aliases matching given player</param>
/// <param name="Origin">Player to scan for aliases</param>
abstract public void getAliases(List<Player> returnPlayers, Player Origin);
abstract public List<Aliases> getAliases(Player Origin);
public List<Player> getPlayerAliases(Player Origin)
{
List<int> databaseIDs = new List<int>();
foreach (Aliases A in getAliases(Origin))
databaseIDs.Add(A.Number);
return clientDB.getPlayers(databaseIDs);
}
/// <summary>
/// Add a player to the server's player list

View File

@ -56,6 +56,7 @@
<Compile Include="Log.cs" />
<Compile Include="Map.cs" />
<Compile Include="Player.cs" />
<Compile Include="Plugin.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Report.cs" />
<Compile Include="Server.cs" />

View File

@ -114,6 +114,31 @@ namespace SharedLibrary
}
}
public static String levelHTMLFormatted(Player.Permission Level)
{
switch (Level)
{
case Player.Permission.User:
return "<span style='color:rgb(87, 150, 66)'>" + Level + "</span>";
case Player.Permission.Moderator:
return "<span style='color:#e7b402'>" + Level + "</span>";
case Player.Permission.Administrator:
return "<span style='color:#ec82de'>" + Level + "</span>";
case Player.Permission.SeniorAdmin:
return "<span style='color:#2eb6bf'>" + Level + "</span>";
case Player.Permission.Owner:
return "<span style='color:rgb(38,120,230)'>" + Level + "</span>";
case Player.Permission.Creator:
return "<span style='color:rgb(38,120,230)'>" + Level + "</span>";
case Player.Permission.Banned:
return "<span style='color:rgb(196, 22, 28)'>" + Level + "</span>";
case Player.Permission.Flagged:
return "<span style='color:rgb(251, 124, 98)'>" + Level + "</span>";
default:
return "<i>" + Level + "</i>";
}
}
public static String nameHTMLFormatted(Player P)
{
switch (P.Level)

View File

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