Apparently I was working with an older codebase.. Oh well, i've merged the changes..

This commit is contained in:
RaidMax 2017-05-26 23:22:50 -05:00
parent 10075b0d3f
commit c151bcbdae
35 changed files with 2056 additions and 414 deletions

File diff suppressed because it is too large Load Diff

View File

@ -14,7 +14,7 @@ namespace IW4MAdmin
public override async Task ExecuteAsync(Event E)
{
await E.Origin.Tell("^5Loaded Plugins:");
foreach (SharedLibrary.Extensions.IPlugin P in PluginImporter.potentialPlugins)
foreach (SharedLibrary.Interfaces.IPlugin P in PluginImporter.potentialPlugins)
{
await E.Origin.Tell(String.Format("^3{0} ^7[v^3{1}^7] by ^5{2}^7", P.Name, P.Version, P.Author));
}

View File

@ -198,18 +198,6 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="IW4MAdmin.exe.config" />
<None Include="m2demo\admin\commands.gsc">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="m2demo\admin\main.gsc">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="m2demo\maps\mp\_load.gsc">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="m2demo\settings\main.gsc">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings">

View File

@ -9,11 +9,11 @@ using Kayak;
namespace IW4MAdmin
{
class Scheduler: ISchedulerDelegate
class Scheduler : ISchedulerDelegate
{
public void OnException(IScheduler scheduler, Exception e)
{
Manager.GetInstance().Logger.Write("Web service has encountered an error - " + e.StackTrace);
Manager.GetInstance().Logger.Write("Web service has encountered an error - " + e.Message);
}
public void OnStop(IScheduler scheduler)
@ -24,27 +24,27 @@ namespace IW4MAdmin
class Request : IHttpRequestDelegate
{
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response)
public void OnRequest(HttpRequestHead request, IDataProducer requestBody, IHttpResponseDelegate response, string IP)
{
// Manager.GetInstance().mainLog.Write("HTTP request received", SharedLibrary.Log.Level.Debug);
// Program.getManager().mainLog.Write("HTTP request received", SharedLibrary.Log.Level.Debug);
NameValueCollection querySet = new NameValueCollection();
if (request.QueryString != null)
querySet = System.Web.HttpUtility.ParseQueryString(SharedLibrary.Utilities.removeNastyChars(request.QueryString));
querySet.Set("IP", ((DefaultKayakServer)(WebService.webService)).clientAddress.Address.ToString());
querySet.Set("IP", IP);
SharedLibrary.HttpResponse requestedPage = WebService.getPage(request.Path, querySet, request.Headers);
var headers = new HttpResponseHead()
{
Status = "200 OK",
Headers = new Dictionary<string, string>()
{
Status = "200 OK",
Headers = new Dictionary<string, string>()
{
{ "Content-Type", requestedPage.contentType },
{ "Content-Length", requestedPage.content.Length.ToString() },
{ "Access-Control-Allow-Origin", "*" },
}
};
};
foreach (var key in requestedPage.additionalHeaders.Keys)
headers.Headers.Add(key, requestedPage.additionalHeaders[key]);

View File

@ -3,7 +3,7 @@ using System.IO;
using System.Collections.Generic;
using System.Reflection;
using SharedLibrary;
using SharedLibrary.Extensions;
using SharedLibrary.Interfaces;
namespace IW4MAdmin
{

View File

@ -58,12 +58,6 @@ namespace IW4MAdmin
if (P.clientID < 0 || P.clientID > (Players.Count-1)) // invalid index
return false;
if (P.Name == null || P.Name == String.Empty || P.Name.Length <= 1)
await this.ExecuteCommandAsync("clientkick " + P.clientID + " \"Please set a name using /name ^7\"");
if (Players.Find(existingPlayer => (existingPlayer != null && existingPlayer.Name.Equals(P.Name)) && existingPlayer.clientID != P.clientID) != null)
await this.ExecuteCommandAsync("clientkick " + P.clientID + " \"Someone is using your name. Set a new name using ^5/name ^7\"");
if (Players[P.clientID] != null && Players[P.clientID].npID == P.npID) // if someone has left and a new person has taken their spot between polls
return true;
@ -224,10 +218,7 @@ namespace IW4MAdmin
Log.Write("Client at " + cNum + " disconnecting...", Log.Level.Debug);
await ExecuteEvent(new Event(Event.GType.Disconnect, "", Leaving, null, this));
lock (Players)
{
Players[cNum] = null;
}
Players[cNum] = null;
ClientNum--;
}
@ -368,7 +359,7 @@ namespace IW4MAdmin
{
await ProcessEvent(E);
foreach (SharedLibrary.Extensions.IPlugin P in PluginImporter.potentialPlugins)
foreach (SharedLibrary.Interfaces.IPlugin P in PluginImporter.potentialPlugins)
{
try
{
@ -385,16 +376,19 @@ namespace IW4MAdmin
}
}
async Task PollPlayersAsync()
async Task PollPlayersAsync()
{
var CurrentPlayers = await this.GetStatusAsync();
for (int i = 0; i < Players.Count; i++)
{
if (CurrentPlayers.Find(p => p.clientID == i) == null && Players[i] != null)
await RemovePlayer(i);
}
foreach (var P in CurrentPlayers)
await AddPlayer(P);
foreach (Player P in CurrentPlayers)
await AddPlayer(P);
}
long l_size = -1;

View File

@ -44,9 +44,19 @@ namespace IW4MAdmin
string[] webConfig = System.IO.File.ReadAllLines("config\\web.cfg");
var address = Dns.GetHostAddresses(webConfig[0])[0];
int port = Convert.ToInt32(webConfig[1]);
using (ss.Listen(new IPEndPoint(address, port)))
S.Start();
try
{
using (ss.Listen(new IPEndPoint(address, port)))
S.Start();
}
catch (Exception e)
{
Console.WriteLine("Unable to start webservice ( port is probably in use ): " + e.Message);
Thread.Sleep(5000);
Environment.Exit(-1);
}
}
catch (Exception)
@ -68,7 +78,7 @@ namespace IW4MAdmin
{
IFile f = new IFile(path.Replace("/", "\\").Substring(1));
if (path.Contains(".css"))
{
HttpResponse css = new HttpResponse();
@ -77,7 +87,7 @@ namespace IW4MAdmin
css.contentType = "text/css";
f.Close();
return css;
}
else if (path.Contains(".js"))
@ -89,8 +99,8 @@ namespace IW4MAdmin
f.Close();
return css;
}
f.Close();
f.Close();
}
requestedPage = new Error404();
@ -173,7 +183,7 @@ namespace IW4MAdmin
{
var info = new List<ServerInfo>();
foreach(Server S in Manager.GetInstance().Servers)
foreach (Server S in Manager.GetInstance().Servers)
{
ServerInfo eachServer = new ServerInfo();
eachServer.serverName = S.getName();
@ -289,7 +299,7 @@ namespace IW4MAdmin
S.ExecuteEvent(remoteEvent);
while(S.commandResult.Count > 0)
while (S.commandResult.Count > 0)
cmd.Result.Add(S.commandResult.Dequeue());
}
else
@ -342,7 +352,8 @@ namespace IW4MAdmin
from = Int32.Parse(querySet["from"]);
List<Penalty> selectedPenalties;
try {
try
{
selectedPenalties = Manager.GetInstance().Servers.First().Bans.OrderByDescending(x => x.When).ToList().GetRange(Convert.ToInt32(querySet["from"]), 15);
}
@ -415,7 +426,7 @@ namespace IW4MAdmin
IFile penalities = new IFile("webfront\\penalties.html");
S.Append(penalities.getLines());
penalities.Close();
S.Append(loadFooter());
return S.ToString();
@ -476,7 +487,7 @@ namespace IW4MAdmin
}
}
class PubbansJSON: IPage
class PubbansJSON : IPage
{
public string getName()
{
@ -531,9 +542,9 @@ namespace IW4MAdmin
PageInfo pi = new PageInfo();
pi.pagePath = p.getPath();
// pi.pageType = p.getPage(querySet, headers).contentType;
// pi.pageType = p.getPage(querySet, headers).contentType;
pi.pageName = p.getName();
pi.visible = p.isVisible();
pi.visible = p.isVisible();
pages.Add(pi);
}
@ -580,17 +591,19 @@ namespace IW4MAdmin
resp.contentType = getContentType();
resp.additionalHeaders = new Dictionary<string, string>();
bool authed = Manager.GetInstance().Servers.First().clientDB.getAdmins().FindAll(x => x.IP == querySet["IP"]).Count > 0;
if (querySet["id"] != null)
{
matchedPlayers.Add(Manager.GetInstance().Servers.First().clientDB.getPlayer(Convert.ToInt32(querySet["id"])));
}
else if(querySet["npID"] != null)
else if (querySet["npID"] != null)
{
matchedPlayers.Add(Manager.GetInstance().Servers.First().clientDB.getPlayers(new List<string> { querySet["npID"] }).First());
}
else if(querySet["name"] != null)
else if (querySet["name"] != null)
{
matchedPlayers = Manager.GetInstance().Servers.First().clientDB.findPlayers(querySet["name"]);
}
@ -607,7 +620,7 @@ namespace IW4MAdmin
{
foreach (var pp in matchedPlayers)
{
if (pp == null) continue;
if (pp == null) continue;
var playerAliases = Manager.GetInstance().Servers.First().getAliases(pp);
PlayerInfo eachPlayer = new PlayerInfo();
@ -617,6 +630,9 @@ namespace IW4MAdmin
eachPlayer.playerName = pp.Name;
eachPlayer.playernpID = pp.npID;
eachPlayer.forumID = -1;
eachPlayer.authed = authed;
if (eachPlayer.forumID < 500000)
eachPlayer.showV2Features = true;
foreach (var a in playerAliases)
{
@ -625,10 +641,10 @@ namespace IW4MAdmin
}
eachPlayer.playerConnections = pp.Connections;
eachPlayer.lastSeen = SharedLibrary.Utilities.timePassed(pp.LastConnection);
eachPlayer.lastSeen = Utilities.timePassed(pp.LastConnection);
pInfo.Add(eachPlayer);
}
}
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(pInfo);
return resp;
@ -669,6 +685,7 @@ namespace IW4MAdmin
{
public string pageName;
public string pagePath;
public string pageType;
public bool visible;
}
@ -685,6 +702,8 @@ namespace IW4MAdmin
public List<string> playerIPs;
public int playerConnections;
public string lastSeen;
public bool showV2Features;
public bool authed;
}
[Serializable]
@ -704,4 +723,4 @@ namespace IW4MAdmin
{
public List<string> Result;
}
}
}

Binary file not shown.

Binary file not shown.

View File

@ -1,9 +1,9 @@
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>IW4MAdmin by RaidMax</title>
<meta name="description" content="Administration tool for IW4M servers. Created by RaidMax">
<meta name="description" content="Administration tool for IW4M servers. IW4MAdmin Created by RaidMax">
<link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
@ -23,7 +23,71 @@ $.getJSON("_userinfo", function(response) {
function showErrorMessage(msg)
{
$('.alertBox').html(msg).addClass('error').slideDown("fast");
message = "An unknown error occurred!";
switch(msg)
{
case 0:
message = "No error";
break;
case 1:
message = "Permission denied";
break;
case 2:
message = "User exists";
break;
case 3:
message = "Invalid user";
break;
case 4:
message = "Incorrect username or password";
break;
case 5:
message = "No credentials entered";
break;
case 6:
message = "User not authorized";
break;
case 7:
message = "Password too long";
break;
case 8:
message = "Username too long";
break;
case 9:
message = "Bad profile data entered";
break;
case 10:
message = "Invalid session";
break;
case 11:
message = "Bad thread content entered";
break;
case 12:
message = "No thread content entered";
break;
case 13:
message = "Thread content too long";
break;
case 14:
message = "Thread title too long";
break;
case 15:
message = "Invalid thread specified";
break;
case 16:
message = "Could not save reply";
break;
case 17:
message = "Invalid category specified";
break;
case 18:
message = "Empty category";
break;
case 19:
message = "Password do not match";
break;
}
$('.alertBox').html(message).addClass('error').slideDown("fast");
}
function parseGet(val) {
@ -74,7 +138,7 @@ function formatMessages(messages)
var chats = "";
$.each(messages, function(i, chat) {
chats +=
"<div class='chatPlayerName tableCell'>" + chat['Name'] + ":</div><div class='chatPlayerMessage tableCell'>" + $("<div/>").html(chat['Message']).text() + "</div> \
"<div class='chatPlayerName tableCell'>" + $("<div/>").html(chat['Name']).text()+ ":</div><div class='chatPlayerMessage tableCell'>" + $("<div/>").html(chat['Message']).text() + "</div> \
<div style='display:table-row'></div>"
});
return chats;
@ -93,9 +157,9 @@ function getPages()
function shouldHideAction(author)
{
// fixme dynamic
if (user.rank == null || author.ranking == null)
if (author.ranking == null)
return " display: none";
else if (user.rank.name == "Moderator" || user.rank.name == "Administrator" || user.username == author.username)
else if (user.user.ranking.name == "Moderator" || user.user.ranking.name == "Administrator" || user.user.id == author.id)
return "";
else {
return " display: none";
@ -107,7 +171,7 @@ function formatPlayers(players)
var p = "";
for (i = 0; i < players.length; i++)
{
p += "<div class='playerName tableCell'><a href=\"/players?id=" + players[1*i]['playerID'] + "\">" + getColorForLevel(players[1*i]['playerLevel'], players[1*i]['playerName']) + "</a></div>";
p += "<div class='playerName tableCell'><a href=\"/players?id=" + players[1*i]['playerID'] + "\">" + getColorForLevel(players[1*i]['playerLevel'], $("<div/>").html(players[1*i]['playerName']).text()) + "</a></div>";
if (i % 2 == 1 && i != 0 )
p += "<div style='display: table-row'></div>";
}
@ -132,7 +196,7 @@ function getDate(datestr)
function checkPrivilege()
{
$.getJSON("_userinfo", function(response) { if (response.rank.id != 1) window.location.replace("home"); else $('.infoBox').show(); });
$.getJSON("_userinfo", function (response) { if (response.user.ranking.id != 1) window.location.replace("home"); else $('.infoBox').show(); });
}
</script>
<body>

View File

@ -15,7 +15,7 @@ div#header #navContainer .navEntry a { padding: 1.2vw; width: 4vw; }
div#header #navContainer .navEntry:hover { background-color: rgb(34, 34, 34); }
div#content { margin: 3em 10%; }
div#content .serverContainer { background-color: #191919; margin: 2em 0; font-size: 1.75vw; }
div#content .serverContainer { background-color: #191919; margin: 2em 0; font-size: 1.25vw; }
div#content hr { border-width: 0; height: 0.25em; background-color: #007ACC; }
div#content .serverInfo { width: 100%; }
div#content .serverInfo .tableCell { padding: 0 0.5em; }
@ -25,10 +25,10 @@ div#content .serverPlayers { text-align: right; width: calc( 100% / 3); backgrou
div#content .serverMap { text-align: center; width: calc( 100% / 3); background-color: #007ACC; }
div#content .serverPlayerList {float: right; margin: 0.5em; }
div#content .serverChatList { float: left; margin: 0.5em }
div#content .playerName { font-size: 1.357vw; color: rgba(78, 140, 77, 0.64); width: 10em; text-align: right; }
div#content .playerName { font-size: 1.1vw; color: rgba(78, 140, 77, 0.64); width: 10em; text-align: right; }
div#content .playerName:hover { color: rgb(0, 122, 204) !important; }
div#content .chatPlayerName { font-weight: bold; font-size: 1.357vw; color:#fff; padding-right: 0.5em; opacity: 0.5; }
div#content .chatPlayerMessage {font-size: 1.357vw; color: #fff; opacity: 1; }
div#content .chatPlayerName { font-weight: bold; font-size: 1.1vw; color:#fff; padding-right: 0.5em; opacity: 0.5; }
div#content .chatPlayerMessage {font-size: 1.1vw; color: #fff; opacity: 1; }
div#content .playerPenalty, div#content .playerInfo { margin: 0 auto; padding: 1em 10px; background-color: #181818; width: calc(100% - 20px); }
div#content .penaltyName { width: 14.28%; }
@ -74,7 +74,7 @@ div.infoBox .header { text-align: center; background-color: #007ACC; padding: 0.
div.infoBox form { padding: 10px; }
div.infoBox { width: 50%; margin: 0 auto; background-color: #181818; border: 1em solid #007ACC; border-width: 0 0 0.25em 0; min-width: 550px; }
div.infoBox input[type="text"], div.infoBox input[type="password"] { width: 70%; }
div.infoBox input[type="submit"] { width: 20%; background-color: #007ACC; font-size: 16pt; border: none; color: #fff; font-size: 15pt; padding: 0.5em 10px; margin: 0.25em; }
div.infoBox input[type="submit"], #userCP input[type="submit"] { width: 20%; background-color: #007ACC; font-size: 16pt; border: none; color: #fff; font-size: 15pt; padding: 0.5em 10px; margin: 0.25em; }
div.alertBox { display: none; margin-top: 15px; margin-left: 15px; }
@ -88,8 +88,8 @@ div#recentTitle { position: relative; top: -1em; }
div#view .threadPreview { background-color: #181818; padding: 0 10px; width: calc(100% - 20px); }
div#view .threadPreview .threadTitle { padding: 0 0.5em; width: 80%; }
div#view .threadPreview .threadInfo { font-size: 9pt; text-align: right; width: 50%; }
div#view .categoryDescription { font-size: 9pt; opacity: 0.5; margin-left: 2em; position: relative; top: -2.5px; }
div#content .individualThreadInfo { border-bottom: 1px solid rgba(255, 255, 255, 0.2); padding: 0.5em 0; display: table; width: 100%; }
div#view .categoryDescription { font-size: 10.5pt; opacity: 0.5; margin-left: 2em; position: relative; top: -2.5px; }
div#content .individualThreadInfo { border-bottom: 1px solid rgba(255, 255, 255, 0.2); padding: 0.5em 1em; display: table; width: calc(100% - 2em); }
div#content .individualThreadInfo:nth-child(3) { border-bottom: none; padding-bottom: 0.5em; }
div#content .individualThreadInfo i { font-size: 16pt; width: 16pt; }
div.title a:link:hover, div.title a:visited:hover { color: #ff6633 !important; }
@ -123,6 +123,7 @@ div#threadContainer .threadContent { margin: 1em 0; font-size: 11pt; word-break
div#threadContainer .threadContent img { max-width: 100%;}
div#threadContainer .threadContent a { color: rgb(0, 122, 204) !important; }
div#threadContainer .threadContent a:hover { color: #fff !important; }
div.threadContent ol, div.threadContent ol { margin: 1em; }
div.categoryThread .threadActions { color: rgba(255, 69, 69, 0.85); font-size: 18pt; width: 19px; }
@ -181,14 +182,19 @@ div#userAvatar { width: 20em; height: 20em; background-size: contain; margin-ri
.themeBlue { color: #007ACC !important; }
.themeBlue:hover { color: #fff !important; }
.themeOrange { color: #ff6633; }
.themeOrage:hover{ color: #007ACC !important; }
.themeOrange:hover{ color: #007ACC !important; }
div.threadInfo .actionHover { float: right; color: rgba(255, 69, 69, 0.85); }
div.threadInfo .actionHover { float: right; color: rgba(255, 69, 69, 0.85); margin: 0 4px; }
.actionHover { cursor: pointer; }
.actionHover:hover { color: #007ACC !important; }
.actionHover.actionEdit { color:#007ACC !important; }
.datThing { background-color: #007ACC; font-size: 16pt; border: none; color: #fff; font-size: 15pt; padding: 0.5em 10px; }
span.light { opacity: 0.5; }
span.userTitle span:hover {color: #007ACC !important; }
input#bannercolor { margin: 0.35em; width: 265px; border: none; height: 45px; }
div#footer { position: fixed; bottom: 0.5em; right: 0.5em; opacity: 0.5; }

View File

@ -17,37 +17,61 @@ function getPrevPage()
else
return 0;
}
function formatHidden(data)
function formatHidden(data, authed)
{
var p = "<div class=\"hiddenWrapper\">Expand<div class=\"hiddenElements\">";
$.each(data, function(i, dat) {
p += "<span>" + dat + "</span><br/>"
})
var p = "<div class=\"hiddenWrapper\"><span>Expand</span><div class=\"hiddenElements\">";
if (authed) {
$.each(data, function (i, dat) {
p += "<span>" + dat + "</span><br/>"
})
}
else
p += "Hidden";
p += "</div></div>"
return p;
}
function printPlayer(player, i)
{
$("#playersTable").append(
"<div class=\"playerInfo table alternate_" + i % 2 + "\"> \
<div class=\"tableCell\"><a href=\"/players?id="+ player['playerID'] + "\">" + player['playerName'] + "</a></div> \
<div class=\"tableCell\">"+ formatHidden(player['playerAliases']) + "</div> \
<div class=\"tableCell\">"+ formatHidden(player['playerIPs']) + "</div> \
<div class=\"tableCell\">"+ getColorForLevel(player['playerLevel'], player['playerLevel']) + "</div> \
<div class=\"tableCell\">"+ player['playerConnections'] + "</div> \
<div class=\"tableCell actionButton\" style='width: 2em;'> \
<a target=\"_blank\" href='http://server.nbsclan.org/screen.php?id=" + player.forumID+ "&name=" + player.playerName + "'> \
var p = "";
p +=
"<div class=\"playerInfo table alternate_" + i % 2 + "\"> \
<div class=\"tableCell\"><a href=\"/players?id=" + player['playerID'] + "\">" + player['playerName'] + "</a></div> \
<div class=\"tableCell\">" + formatHidden(player['playerAliases'], player.authed) + "</div> \
<div class=\"tableCell\">" + formatHidden(player['playerIPs'], player.authed) + "</div> \
<div class=\"tableCell\">" + getColorForLevel(player['playerLevel'], player['playerLevel']) + "</div> \
<div class=\"tableCell\">" + player['playerConnections'] + "</div>";
if (player.showV2Features)
{
p +=
"<div class=\"tableCell actionButton\" style='width: 2em;'> \
<a target=\"_blank\" href='http://server.nbsclan.org/screen.php?id=" + player.forumID + "&name=" + player.playerName + "'> \
<i class=\"fa fa-camera\" aria-hidden=\"true\"></i> \
</a> \
<a target=\"_blank\" href='https://v2.mcsebi.ru/memberlist.php?mode=viewprofile&u=" + player.forumID + "'> \
<i class=\"fa fa-user tableCell\" aria-hidden=\"true\"></i> \
</a> \
</div> \
<div class=\"tableCell alignRight\">"+ checkJustNow(player['lastSeen']) + "</div> \
</div>"
)
</div> ";
}
else
{
p+=
"<div class=\"tableCell\" style='width: 2em;'><i class=\"fa fa-ban\" aria-hidden=\"true\"></i></div>"
}
p +=
"<div class=\"tableCell alignRight\">" + checkJustNow(player['lastSeen']) + "</div> \
</div>";
$("#playersTable").append(p);
}
function getPlayer(ident, identValue)
@ -59,7 +83,7 @@ function getPlayer(ident, identValue)
$.each(result, function(i, player) {
printPlayer(player, i);
});
}).done(function (data) { $(".loader").fadeOut(); });
}).done(function (data) { $(".loader").fadeOut(); });
}
$( document ).ready(function() {
@ -72,8 +96,8 @@ $( document ).ready(function() {
}
});
$('#content').on('click', '.hiddenWrapper', function(){
$(this).find('.hiddenElements').toggle()
$('#content').on('click', 'div.hiddenWrapper span', function(){
$(this).parent().find('.hiddenElements').toggle()
});
</script>

View File

@ -1,6 +1,6 @@
using System;
using SharedLibrary;
using SharedLibrary.Extensions;
using SharedLibrary.Interfaces;
using System.Threading.Tasks;
namespace Auto_Restart_Plugin

View File

@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.Text;
using SharedLibrary;
using SharedLibrary.Extensions;
using SharedLibrary.Interfaces;
using System.Threading.Tasks;
namespace EventAPI

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using SharedLibrary;
using System.Collections.Specialized;
@ -17,7 +18,7 @@ namespace MessageBoard.Forum
private const int MAX_SESSIONS = 64;
public const int TITLE_MAXLENGTH = 30;
public const int CONTENT_MAXLENGTH = 8192;
public const int USERNAME_MAXLENGTH = 16;
public const int USERNAME_MAXLENGTH = 30;
public const int PASSWORD_MAXLENGTH = 64;
public Rank guestRank;
@ -36,6 +37,7 @@ namespace MessageBoard.Forum
USER_NOTAUTHORIZED,
USER_PASSWORDTOOLONG,
USER_USERNAMETOOLONG,
USER_BADPROFILEDATA,
SESSION_INVALID,
THREAD_BADDATA,
THREAD_EMPTYDATA,
@ -44,7 +46,8 @@ namespace MessageBoard.Forum
THREAD_INVALID,
REPLY_SAVEFAILED,
CATEGORY_INVALID,
CATEGORY_EMPTY
CATEGORY_EMPTY,
USER_MISMATCHEDPASSWORD
}
public Manager()
@ -60,13 +63,13 @@ namespace MessageBoard.Forum
{
Session newSession = getSession(sessionID);
newSession.sessionStartTime = DateTime.Now;
Console.WriteLine("Matching session was found - {0}", sessionID);
//Console.WriteLine("Matching session was found - {0}", sessionID);
addSession(newSession);
}
catch (Exceptions.SessionException)
{
Console.WriteLine("No session was found so we are adding a new one");
//Console.WriteLine("No session was found so we are adding a new one");
Session newSession = new Session(new User(), sessionID);
addSession(newSession);
}
@ -95,6 +98,16 @@ namespace MessageBoard.Forum
return requestedUser;
}
public User getUser(string username)
{
User requestedUser = database.getUser(username);
if (requestedUser == null)
throw new Exceptions.UserException("User not found");
return requestedUser;
}
public ForumThread getThread(int threadID)
{
ForumThread requestedThread = database.getThread(threadID);
@ -150,7 +163,7 @@ namespace MessageBoard.Forum
if (activeSessions.Count >= MAX_SESSIONS)
activeSessions.RemoveAt(0);
//activeSessions.RemoveAll(x => (x.sessionID == sess.sessionID && sess.sessionUser.ranking.equivalentRank > x.sessionUser.ranking.equivalentRank));
activeSessions.RemoveAll(x => x.sessionUser.ranking.name == "Guest" && x.sessionID == sess.sessionID);
//Console.WriteLine(String.Format("Adding new session [{0}] [{1}]", sess.sessionID, sess.sessionUser.username));
@ -158,7 +171,7 @@ namespace MessageBoard.Forum
activeSessions.Add(sess);
// if it's a guest session, we don't want to save them in the database...
if (sess.sessionUser.ranking.equivalentRank > Player.Permission.User)
if (sess.sessionUser.ranking.name != "Guest")
{
database.setSession(sess.sessionUser.id, sess.sessionID);
sess.sessionUser.lastLogin = DateTime.Now;
@ -171,6 +184,24 @@ namespace MessageBoard.Forum
public void removeSession(string sessID)
{
activeSessions.RemoveAll(x => x.sessionID == sessID);
database.removeSession(sessID);
}
public ProfileSettings getProfileSettings(int userid)
{
var retrieved = database.getProfileSettings(userid);
if (retrieved == null)
{
if (userid > 0)
{
var profile = new ProfileSettings(userid);
database.addProfileSettings(profile);
return profile;
}
return new ProfileSettings(0);
}
else
return retrieved;
}
public ErrorCode addUser(User newUser, Session userSession)
@ -183,6 +214,8 @@ namespace MessageBoard.Forum
newUser.ranking = AdminRank;
User createdUser = database.addUser(newUser, userSession);
database.addProfileSettings(new ProfileSettings(createdUser.id));
removeSession(userSession.sessionID);
return addSession(new Session(createdUser, userSession.sessionID));
}
@ -191,6 +224,11 @@ namespace MessageBoard.Forum
database.updateUser(updatedUser);
}
public void updateUserProfile(ProfileSettings updatedUserProfile)
{
database.updateProfileSettings(updatedUserProfile);
}
public ErrorCode updateThread(ForumThread newThread)
{
if (database.updateThread(newThread))
@ -218,7 +256,7 @@ namespace MessageBoard.Forum
public ErrorCode authorizeUser(string username, string password, string sessionID)
{
User toAuth = database.getUser(username);
User toAuth = database.getUser(username.ToLower());
if (toAuth == null)
return ErrorCode.USER_BADCREDENTIALS;
@ -270,6 +308,8 @@ namespace MessageBoard.Forum
var registerJSON = new Pages.RegisterJSON();
var userinfoJSON = new Pages.userinfoJSON();
var viewUser = new Pages.ViewUser();
var userCP = new Pages.UserCP();
var updateUserJSON = new Pages.updateUserJSON();
var categoriesJSON = new Pages.categoriesJSON();
var category = new Pages.ViewCategory();
var categorythreadsJSON = new Pages.categorythreadsJSON();
@ -289,6 +329,8 @@ namespace MessageBoard.Forum
forumPages.Add(registerJSON);
forumPages.Add(userinfoJSON);
forumPages.Add(viewUser);
forumPages.Add(userCP);
forumPages.Add(updateUserJSON);
forumPages.Add(categoriesJSON);
forumPages.Add(category);
forumPages.Add(categorythreadsJSON);
@ -308,6 +350,8 @@ namespace MessageBoard.Forum
SharedLibrary.WebService.pageList.Add(registerJSON);
SharedLibrary.WebService.pageList.Add(userinfoJSON);
SharedLibrary.WebService.pageList.Add(viewUser);
SharedLibrary.WebService.pageList.Add(userCP);
SharedLibrary.WebService.pageList.Add(updateUserJSON);
SharedLibrary.WebService.pageList.Add(categoriesJSON);
SharedLibrary.WebService.pageList.Add(category);
SharedLibrary.WebService.pageList.Add(categorythreadsJSON);
@ -366,7 +410,7 @@ namespace MessageBoard.Forum
if (requestHeaders.ContainsKey("Cookie"))
{
Console.WriteLine("JSON request contains session header - " + requestHeaders["Cookie"]);
//Console.WriteLine("JSON request contains session header - " + requestHeaders["Cookie"]);
string cookie = requestHeaders["Cookie"].Split('=')[1];
Plugin.Main.forum.startSession(cookie);
currentSession = Plugin.Main.forum.getSession(cookie);
@ -552,6 +596,30 @@ namespace MessageBoard.Forum
}
}
public class UserCP : ForumPage
{
public UserCP() : base(false)
{
}
public override string getName()
{
return "Forum - User Control Panel";
}
public override string getPath()
{
return base.getPath() + "/usercp";
}
public override string getContent(NameValueCollection querySet, IDictionary<string, string> headers)
{
string content = loadFile("forum\\usercp.html");
return templatation(content);
}
}
public class ViewThread : ForumPage
{
public ViewThread() : base(false)
@ -622,10 +690,29 @@ namespace MessageBoard.Forum
result.destination = base.getPath() + "/error";
try {
string username = DNA.Text.TextEngine.Text(querySet["username"]);
string password = DNA.Text.TextEngine.Text(querySet["password"]);
string email = DNA.Text.TextEngine.Text(querySet["email"]);
bool validEmail = Regex.IsMatch(email,
@"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
@"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
RegexOptions.IgnoreCase) && email.Length < Manager.PASSWORD_MAXLENGTH;
if (!validEmail)
throw new Exceptions.UserException("Email is invalid");
if (username.Length > Manager.USERNAME_MAXLENGTH)
throw new Exceptions.UserException("Username is too long");
if (password.Length > Manager.PASSWORD_MAXLENGTH)
throw new Exceptions.UserException("Password is too long");
byte[] passwordSalt = Encryption.PasswordHasher.GenerateSalt();
string b64PasswordHash = Convert.ToBase64String(Encryption.PasswordHasher.ComputeHash(querySet["password"], passwordSalt));
string b64PasswordHash = Convert.ToBase64String(Encryption.PasswordHasher.ComputeHash(password, passwordSalt));
User registeringUser = new User(querySet["username"], querySet["hiddenUsername"], querySet["email"], b64PasswordHash, Convert.ToBase64String(passwordSalt), Plugin.Main.forum.UserRank);
User registeringUser = new User(username, querySet["hiddenUsername"], email, b64PasswordHash, Convert.ToBase64String(passwordSalt), Plugin.Main.forum.UserRank);
currentSession = new Session(registeringUser, currentSession.sessionID);
var addUserResult = Plugin.Main.forum.addUser(registeringUser, currentSession);
@ -643,7 +730,9 @@ namespace MessageBoard.Forum
}
}
catch (Exception E) {
catch (Exception E)
{
//logme
result.errorCode = Manager.ErrorCode.USER_INVALID;
}
@ -665,11 +754,12 @@ namespace MessageBoard.Forum
UserInfo info = new UserInfo();
bool validUserSelection = true;
User requestedUser = null;
try
{
requestedUser = Plugin.Main.forum.getUser(Convert.ToInt32(querySet["id"]));
int userid = Convert.ToInt32(querySet["id"]);
info.user = Plugin.Main.forum.getUser(userid);
info.profile = Plugin.Main.forum.getProfileSettings(userid);
}
catch (FormatException)
@ -684,41 +774,120 @@ namespace MessageBoard.Forum
validUserSelection = false;
}
if (validUserSelection)
if (!validUserSelection)
{
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(requestedUser);
info.user = currentSession.sessionUser;
try
{
info.profile = Plugin.Main.forum.getProfileSettings(info.user.id);
}
catch (Exceptions.UserException)
{
//logme
}
}
else
/*// this should not be a thing but ok...
Player matchedPlayer = Plugin.Main.stupidServer.clientDB.getPlayer(querySet["ip"]);
if (matchedPlayer != null)
info.matchedUsername = matchedPlayer.Name;*/
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(info);
return resp;
}
}
public class updateUserJSON : JSONPage
{
public override string getPath()
{
return base.getPath() + "/_updateuser";
}
public override HttpResponse getPage(NameValueCollection querySet, IDictionary<string, string> requestHeaders)
{
var resp = base.getPage(querySet, requestHeaders);
var aResp = new ActionResponse();
bool passwordUpdateRequest = false;
if (querySet["username"] == null || currentSession.sessionUser.id == 0)
aResp.errorCode = Manager.ErrorCode.USER_INVALID;
else if (querySet["bannercolor"] == null)
aResp.errorCode = Manager.ErrorCode.USER_BADPROFILEDATA;
if (querySet["updatedpassword"] != null && querySet["updatedpasswordrepeat"] != null && querySet["updatedpassword"].Length > 0 && querySet["updatedpasswordrepeat"].Length > 0)
passwordUpdateRequest = true;
if (aResp.errorCode == Manager.ErrorCode.NO_ERROR)
{
if (querySet.Get("setavatarurl") != null)
string username = DNA.Text.TextEngine.Text(querySet["username"]);
string bannercolor = DNA.Text.TextEngine.Text(querySet["bannercolor"]);
string avatarURL = DNA.Text.TextEngine.Text(querySet["avatarurl"]);
string password = null;
if (passwordUpdateRequest)
{
if (currentSession.sessionUser.ranking.name != "Guest")
password = DNA.Text.TextEngine.Text(querySet["updatedpassword"]);
string passwordRepeat = DNA.Text.TextEngine.Text(querySet["updatedpasswordrepeat"]);
if (!password.Equals(passwordRepeat))
{
currentSession.sessionUser.avatarURL = querySet["setavatarurl"];
Plugin.Main.forum.updateUser(currentSession.sessionUser);
resp.content = "OK!";
return resp;
password = null;
aResp.errorCode = Manager.ErrorCode.USER_MISMATCHEDPASSWORD;
}
else if (password.Length > Manager.PASSWORD_MAXLENGTH)
{
password = null;
aResp.errorCode = Manager.ErrorCode.USER_PASSWORDTOOLONG;
}
}
User existingUser = null;
try
{
existingUser = Plugin.Main.forum.getUser(username);
}
catch (Exceptions.UserException)
{
}
if (existingUser != null && existingUser.id != currentSession.sessionUser.id)
aResp.errorCode = Manager.ErrorCode.USER_DUPLICATE;
else
{
info.email = currentSession.sessionUser.email;
info.username = currentSession.sessionUser.username;
info.rank = currentSession.sessionUser.ranking;
var profile = Plugin.Main.forum.getProfileSettings(currentSession.sessionUser.id);
if (username.Length <= Manager.USERNAME_MAXLENGTH)
currentSession.sessionUser.updateUsername(username);
else
aResp.errorCode = Manager.ErrorCode.USER_USERNAMETOOLONG;
currentSession.sessionUser.updateAvatar(avatarURL);
// this should not be a thing but ok...
Player matchedPlayer = Plugin.Main.stupidServer.clientDB.getPlayer(querySet["ip"]);
if (passwordUpdateRequest && aResp.errorCode == Manager.ErrorCode.NO_ERROR)
{
byte[] passwordSalt = Encryption.PasswordHasher.GenerateSalt();
string b64PasswordHash = Convert.ToBase64String(Encryption.PasswordHasher.ComputeHash(password, passwordSalt));
currentSession.sessionUser.updatePassword(Convert.ToBase64String(passwordSalt), b64PasswordHash);
}
if (matchedPlayer != null)
info.matchedUsername = matchedPlayer.Name;
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(info);
Plugin.Main.forum.updateUser(currentSession.sessionUser);
if (bannercolor.Length == 7)
profile.bannerColor = bannercolor;
Plugin.Main.forum.updateUserProfile(profile);
}
}
return resp;
aResp.success = aResp.errorCode == Manager.ErrorCode.NO_ERROR;
if (aResp.success)
aResp.destination = "usercp";
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(aResp);
return resp;
}
}
@ -737,7 +906,10 @@ namespace MessageBoard.Forum
try
{
var result = Plugin.Main.forum.authorizeUser(querySet["username"], querySet["password"], currentSession.sessionID);
string username = DNA.Text.TextEngine.Text(querySet["username"]);
string password = DNA.Text.TextEngine.Text(querySet["password"]);
var result = Plugin.Main.forum.authorizeUser(username, password, currentSession.sessionID);
aResp.success = result == Manager.ErrorCode.NO_ERROR;
aResp.errorCode = result;
aResp.destination = "home";
@ -881,13 +1053,24 @@ namespace MessageBoard.Forum
var thread = Plugin.Main.forum.getThread(Convert.ToInt32(querySet["id"]));
if ((thread.threadCategory.permissions.Find(x => x.rankID == currentSession.sessionUser.ranking.id).actionable & Permission.Action.READ) != Permission.Action.READ)
throw new Exceptions.PermissionException("You cannot view this post");
throw new Exceptions.PermissionException("User cannot view this post");
var replies = Plugin.Main.forum.getReplies(thread.id);
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(new ThreadView(thread, replies));
aResp.success = true;
}
else if (querySet.Get("replyid") != null)
{
var thread = Plugin.Main.forum.getReply(Convert.ToInt32(querySet["replyid"]));
//if ((thread.threadCategory.permissions.Find(x => x.rankID == currentSession.sessionUser.ranking.id).actionable & Permission.Action.READ) != Permission.Action.READ)
// throw new Exceptions.PermissionException("User cannot view this post");
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(thread);
aResp.success = true;
}
}
catch (FormatException)
@ -961,15 +1144,15 @@ namespace MessageBoard.Forum
else
{
//fixsecurity
var markdownParser = new MarkdownDeep.Markdown();
string markdownContent = markdownParser.Transform(querySet["content"]);
markdownContent = Uri.EscapeDataString(markdownContent);
string title = Uri.EscapeDataString(querySet["title"]);
var fmtr = new DNA.Text.BBCodeFormatter();
string content = fmtr.Format(Uri.UnescapeDataString(querySet["content"]));
string title = DNA.Text.TextEngine.Text(Uri.UnescapeDataString(querySet["title"]));
if (thread.updateTitle(title) && thread.updateContent(markdownContent))
if (thread.updateTitle(title) && thread.updateContent(content))
{
aResp.errorCode = Plugin.Main.forum.updateThread(thread);
aResp.success = aResp.errorCode == Manager.ErrorCode.NO_ERROR;
aResp.destination = "thread?id=" + thread.id;
}
else
aResp.errorCode = Manager.ErrorCode.THREAD_EMPTYDATA;
@ -980,7 +1163,7 @@ namespace MessageBoard.Forum
else if (querySet.Get("replyid") != null)
{
var reply = Plugin.Main.forum.getReply(Convert.ToInt32(querySet["replyid"]));
if (currentSession.sessionUser.id == 0 || reply.author.id != currentSession.sessionUser.id && (reply.threadCategory.permissions.Find(x => x.rankID == currentSession.sessionUser.ranking.id).actionable & Permission.Action.MODIFY) != Permission.Action.MODIFY)
throw new Exceptions.PermissionException("User cannot modify this reply");
@ -992,6 +1175,40 @@ namespace MessageBoard.Forum
aResp.destination = "thread?id=" + reply.threadid;
}
else if (querySet.Get("content") != null)
{
if (querySet.Get("content") == null || querySet.Get("title") == null)
throw new Exceptions.ThreadException("Invalid update data");
if (querySet.Get("content").Length > Manager.CONTENT_MAXLENGTH)
{
aResp.errorCode = Manager.ErrorCode.THREAD_CONTENTTOOLONG;
}
else if (querySet.Get("title").Length > Manager.TITLE_MAXLENGTH)
{
aResp.errorCode = Manager.ErrorCode.THREAD_TITLETOOLONG;
}
else
{
int threadID = Convert.ToInt32(querySet["threadid"]);
//fixsecurity
var fmtr = new DNA.Text.BBCodeFormatter();
string content = fmtr.Format(Uri.UnescapeDataString(querySet["content"]));
string title = DNA.Text.TextEngine.Text(Uri.UnescapeDataString(querySet["title"]));
if (reply.updateTitle(title) && reply.updateContent(content))
{
aResp.errorCode = Plugin.Main.forum.updateReply(reply);
aResp.success = aResp.errorCode == Manager.ErrorCode.NO_ERROR;
aResp.destination = "thread?id=" + threadID;
}
else
aResp.errorCode = Manager.ErrorCode.THREAD_EMPTYDATA;
}
}
}
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(aResp);
@ -1043,15 +1260,14 @@ namespace MessageBoard.Forum
if (querySet["content"].Length < Manager.CONTENT_MAXLENGTH && querySet["title"].Length <= Manager.TITLE_MAXLENGTH)
{
var markdownParser = new MarkdownDeep.Markdown();
string markdownContent = markdownParser.Transform(querySet["content"]);
markdownContent = Uri.EscapeDataString(markdownContent);
string title = Uri.EscapeDataString(querySet["title"]);
var fmtr = new DNA.Text.BBCodeFormatter();
string content = fmtr.Format(Uri.UnescapeDataString(querySet["content"]));
string title = DNA.Text.TextEngine.Text(Uri.UnescapeDataString(querySet["title"]));
if (querySet.Get("threadid") != null)
{
var replyThread = Plugin.Main.forum.getThread(Convert.ToInt32(querySet.Get("threadid")));
var reply = new Post(title, replyThread.getID(), markdownContent, currentSession.sessionUser);
var reply = new Post(title, replyThread.getID(), content, currentSession.sessionUser);
aResp.errorCode = Plugin.Main.forum.addPost(replyThread, reply);
aResp.destination = String.Format("thread?id={0}", replyThread.id);
@ -1064,7 +1280,7 @@ namespace MessageBoard.Forum
if ((threadCategory.permissions.Find(x => x.rankID == currentSession.sessionUser.ranking.id).actionable & Permission.Action.WRITE) == Permission.Action.WRITE)
{
ForumThread newThread = new ForumThread(title, markdownContent, currentSession.sessionUser, threadCategory);
ForumThread newThread = new ForumThread(title, content, currentSession.sessionUser, threadCategory);
aResp.errorCode = Plugin.Main.forum.addThread(newThread);
aResp.destination = String.Format("category?id={0}", threadCategory.id);
@ -1118,6 +1334,7 @@ namespace MessageBoard.Forum
if (s.sessionUser.ranking.id > 0 && (DateTime.Now - s.sessionStartTime).TotalMinutes < 5 && s.sessionUser.username != "Guest")
stats.onlineUsers.Add(s.sessionUser);
}
stats.onlineUsers.OrderByDescending(x => x.ranking.equivalentRank);
resp.content = Newtonsoft.Json.JsonConvert.SerializeObject(stats);
return resp;

View File

@ -37,13 +37,6 @@
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj">
<Project>{d51eeceb-438a-47da-870f-7d7b41bc24d6}</Project>
<Name>SharedLibrary</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Compile Include="Encryption.cs" />
<Compile Include="Events.cs" />
@ -58,11 +51,15 @@
<Compile Include="User.cs" />
</ItemGroup>
<ItemGroup>
<Reference Include="CodeKicker.BBCode, Version=5.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\CodeKicker.BBCode.5.0.0.0\lib\net35\CodeKicker.BBCode.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="CryptSharp">
<HintPath>..\packages\CryptSharp.1.2.0.1\lib\net35\CryptSharp.dll</HintPath>
</Reference>
<Reference Include="MarkdownDeep, Version=1.5.4615.26275, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MarkdownDeep.NET.1.5\lib\.NetFramework 3.5\MarkdownDeep.dll</HintPath>
<Reference Include="DNA.Text, Version=2.1.1.10633, Culture=neutral, PublicKeyToken=f393b6ce92960100, processorArchitecture=MSIL">
<HintPath>..\packages\DNA.Text.2.1.1.10633\lib\DNA.Text.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Newtonsoft.Json">
@ -71,10 +68,16 @@
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Data.SQLite">
<HintPath>..\SharedLibrary\bin\Release\System.Data.SQLite.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Web" />
<Reference Include="System.XML" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
@ -99,6 +102,19 @@
<Content Include="forum\user.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="forum\usercp.html">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SharedLibrary\SharedLibrary.csproj">
<Project>{d51eeceb-438a-47da-870f-7d7b41bc24d6}</Project>
<Name>SharedLibrary</Name>
<Private>False</Private>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
@ -106,8 +122,10 @@
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Admin\bin\$(ConfigurationName)\plugins\MessageBoardPlugin.dll"
xcopy /E /Y "$(TargetDir)forum" "$(SolutionDir)Admin\bin\$(ConfigurationName)\forum"
copy /Y "$(TargetDir)MarkdownDeep.dll" "$(SolutionDir)Admin\bin\$(ConfigurationName)\lib\MarkdownDeep.dll"
copy /Y "$(TargetDir)DNA.Text.dll" "$(SolutionDir)Admin\bin\$(ConfigurationName)\lib\DNA.Text.dll"
copy /Y "$(TargetDir)CryptSharp.dll" "$(SolutionDir)Admin\bin\$(ConfigurationName)\lib\CryptSharp.dll"
copy /Y "$(TargetDir)CodeKicker.BBcode.dll" "$(SolutionDir)Admin\bin\$(ConfigurationName)\lib\CodeKicker.BBcode.dll"
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)BUILD\plugins\"</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -1,6 +1,6 @@
using System;
using SharedLibrary;
using SharedLibrary.Extensions;
using SharedLibrary.Interfaces;
using System.Threading.Tasks;
namespace MessageBoard.Plugin
@ -36,11 +36,8 @@ namespace MessageBoard.Plugin
public async Task OnLoad()
{
await Task.Run(() =>
{
forum = new Forum.Manager();
forum.Start();
});
forum = new Forum.Manager();
forum.Start();
}
public async Task OnUnload()

View File

@ -13,10 +13,10 @@ namespace MessageBoard.Storage
{
if (!System.IO.File.Exists(FileName))
{
string createClientTable = @"CREATE TABLE [USERS] (
string createClientTable = @"CREATE TABLE IF NOT EXISTS [USERS] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[ranking] INTEGER DEFAULT 0,
[username] TEXT NOT NULL,
[username] TEXT COLLATE NOCASE NOT NULL,
[email] TEXT NOT NULL,
[passwordhash] TEXT NOT NULL,
[passwordsalt] TEXT NOT NULL,
@ -26,26 +26,26 @@ namespace MessageBoard.Storage
[avatarurl] TEXT
);";
string createSessionTable = @"CREATE TABLE [SESSIONS] (
string createSessionTable = @"CREATE TABLE IF NOT EXISTS [SESSIONS] (
[sessionid] TEXT NOT NULL,
[sessionuserid] INTEGER NOT NULL,
FOREIGN KEY(sessionuserid) REFERENCES USERS(id)
);";
string createRankingTable = @"CREATE TABLE [RANKS] (
string createRankingTable = @"CREATE TABLE IF NOT EXISTS [RANKS] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[name] TEXT UNIQUE NOT NULL,
[equivalentrank] INTEGER DEFAULT 0
);";
string createCategoryTable = @"CREATE TABLE [CATEGORIES] (
string createCategoryTable = @"CREATE TABLE IF NOT EXISTS [CATEGORIES] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[title] TEXT NOT NULL,
[description] TEXT NOT NULL,
[permissions] BLOB
);";
string createThreadTable = @"CREATE TABLE [THREADS] (
string createThreadTable = @"CREATE TABLE IF NOT EXISTS [THREADS] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[title] TEXT NOT NULL,
[categoryid] INTEGER NOT NULL,
@ -59,7 +59,7 @@ namespace MessageBoard.Storage
FOREIGN KEY(categoryid) REFERENCES CATEGORIES(id)
);";
string createReplyTable = @"CREATE TABLE [REPLIES] (
string createReplyTable = @"CREATE TABLE IF NOT EXISTS [REPLIES] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[title] TEXT NOT NULL,
[authorid] INT NOT NULL,
@ -72,6 +72,15 @@ namespace MessageBoard.Storage
FOREIGN KEY(threadid) REFERENCES THREADS(id)
);";
string createUserProfileTable = @"CREATE TABLE IF NOT EXISTS [PROFILES] (
[id] INTEGER PRIMARY KEY AUTOINCREMENT,
[userid] INTEGER NOT NULL,
[showemail] INTEGER DEFAULT 1,
[bannercolor] TEXT DEFAULT '#ff6633',
[birthday] TEXT,
[showage] INTEGER DEFAULT 0
);";
ExecuteNonQuery(createClientTable);
ExecuteNonQuery(createSessionTable);
@ -79,6 +88,7 @@ namespace MessageBoard.Storage
ExecuteNonQuery(createCategoryTable);
ExecuteNonQuery(createThreadTable);
ExecuteNonQuery(createReplyTable);
ExecuteNonQuery(createUserProfileTable);
Rank guestRank = new Rank(1, "Guest", SharedLibrary.Player.Permission.User);
Rank userRank = new Rank(2, "User", SharedLibrary.Player.Permission.Trusted);
@ -144,6 +154,11 @@ namespace MessageBoard.Storage
return getSession(sessionID);
}
public void removeSession(string sessionID)
{
ExecuteNonQuery(String.Format("DELETE FROM SESSIONS WHERE sessionid = '{0}'", sessionID));
}
public bool updateSession(string sessionID, int userID)
{
if (getSession(sessionID) == null)
@ -550,5 +565,59 @@ namespace MessageBoard.Storage
return 0;
}
#endregion
#region PROFILES
private ProfileSettings getProfileFromDataTable(DataTable Result)
{
if (Result != null && Result.Rows.Count > 0)
{
DataRow ResponseRow = Result.Rows[0];
int id = Convert.ToInt32(ResponseRow["id"].ToString());
int userID = Convert.ToInt32(ResponseRow["userid"].ToString());
bool showEmail = Convert.ToBoolean(Convert.ToInt32(ResponseRow["showemail"].ToString()));
string bannerColor = ResponseRow["bannercolor"].ToString();
DateTime birthday = DateTime.Parse(ResponseRow["birthday"].ToString());
bool showAge = Convert.ToBoolean(Convert.ToInt32(ResponseRow["showage"].ToString()));
ProfileSettings foundProfile = new ProfileSettings(id, userID, showEmail, bannerColor, birthday, showAge);
return foundProfile;
}
return null;
}
private Dictionary<string, object> getDataTableFromProfile(ProfileSettings addedSettings)
{
Dictionary<String, object> newSettings = new Dictionary<String, object>();
if(addedSettings.id > 0)
newSettings.Add("id", addedSettings.id);
newSettings.Add("userid", addedSettings.userid);
newSettings.Add("showemail", Convert.ToInt32(addedSettings.showEmail));
newSettings.Add("bannercolor", addedSettings.bannerColor);
newSettings.Add("birthday", SharedLibrary.Utilities.DateTimeSQLite(addedSettings.birthday));
newSettings.Add("showage", Convert.ToInt32(addedSettings.showAge));
return newSettings;
}
public ProfileSettings getProfileSettings(int userid)
{
DataTable Result = GetDataTable("PROFILES", new KeyValuePair<string, object>("userid", userid));
return getProfileFromDataTable(Result);
}
public bool addProfileSettings(ProfileSettings newProfile)
{
return Insert("PROFILES", getDataTableFromProfile(newProfile));
}
public bool updateProfileSettings(ProfileSettings updatedProfile)
{
return Update("PROFILES", getDataTableFromProfile(updatedProfile), new KeyValuePair<string, object>("userid", updatedProfile.userid));
}
#endregion
}
}

View File

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MessageBoard
{
@ -66,6 +64,7 @@ namespace MessageBoard
{
public string title { get; private set; }
public string content { get; private set; }
public string formattedContent { get; private set; }
public User author { get; private set; }
public Category threadCategory { get; private set; }
public DateTime creationDate { get; private set; }
@ -91,7 +90,7 @@ namespace MessageBoard
throw new Exceptions.ThreadException("Title is empty");
this.title = title;
this.content = content;
this.content = content;
this.author = author;
this.threadCategory = threadCategory;
creationDate = DateTime.Now;
@ -114,6 +113,7 @@ namespace MessageBoard
this.replies = replies;
this.title = title;
this.content = content;
this.formattedContent = CodeKicker.BBCode.BBCode.ToHtml(this.content);
this.author = author;
this.threadCategory = threadCategory;
this.creationDate = creationDate;

View File

@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLibrary;
namespace MessageBoard
@ -96,13 +94,75 @@ namespace MessageBoard
{
return this.passwordHash;
}
public void updateUsername(string username)
{
if (username != null && username.Length > 0)
this.username = username;
}
public void updateAvatar(string avatarURL)
{
this.avatarURL = avatarURL;
}
public void updatePassword(string salt, string hash)
{
if (salt.Length > 0 && hash.Length > 0)
{
passwordHash = hash;
passwordSalt = salt;
}
}
}
public class ProfileSettings
{
public int id { get; private set; }
public int userid { get; private set; }
public bool showEmail { get; private set; }
public string bannerColor;
public DateTime birthday { get; private set; }
public bool showAge { get; private set; }
public ProfileSettings(int userid)
{
id = 0;
this.userid = userid;
showEmail = true;
showAge = true;
}
public ProfileSettings(int id, int userid, bool showEmail, string bannerColor, DateTime birthday, bool showAge)
{
this.id = id;
this.userid = userid;
this.showEmail = showEmail;
this.bannerColor = bannerColor;
this.birthday = birthday;
this.showAge = showAge;
}
public void hideEmail(bool shouldHide)
{
if (shouldHide)
showEmail = false;
else
showEmail = true;
}
public void hideAge(bool shouldHide)
{
if (shouldHide)
showAge = false;
else
showAge = true;
}
}
public struct UserInfo
{
public string username;
public string email;
public string matchedUsername;
public Rank rank;
public User user;
public ProfileSettings profile;
}
}

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.0.1" newVersion="4.0.0.1"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup></configuration>

View File

@ -1,38 +1,43 @@
<div id="threadContainer">
<div id="textNav"><a class="themeBlue" href="home">Home</a> &raquo; </div>
<hr/>
<div class="threadStart table" style="width: 100%;">
<div class="userInfo tableCell">
<div class="userAvatar">
<i class="fa fa-user-secret" aria-hidden="true" style="font-size: 8em;"></i>
</div>
<a class="userProfileLink" href=""><span class="userTitle">_</span></a><br/>
<span style="font-size: 9pt;" class="timePosted">_</span>
<div id="textNav"><a class="themeBlue" href="home">Home</a> &raquo; </div>
<hr />
<div class="threadStart table" style="width: 100%;">
<div class="userInfo tableCell">
<div class="userAvatar">
<i class="fa fa-user-secret" aria-hidden="true" style="font-size: 8em;"></i>
</div>
<a class="userProfileLink" href=""><span class="userTitle">_</span></a><br />
<span style="font-size: 9pt;" class="timePosted">_</span>
</div>
<div class="threadInfo tableCell">
<div class="threadTitle" style="float: left;">_</div>
<div style="float: right;" id="replyThreadCaption">
<i class="fa fa-reply" aria-hidden="true"></i>
Reply
</div>
<div style="clear: both;"></div>
<div style="float: right; display: none;" id="editThreadCaption">
<i class="fa fa-pencil-square-o" aria-hidden="true"></i>
Edit
</div>
<div class="threadContent">_</div>
</div>
</div>
<div class="threadInfo tableCell">
<div class="threadTitle" style="float: left;">_</div>
<div style="float: right;" id="replyThreadCaption">
<i class="fa fa-reply" aria-hidden="true"></i>
Reply
</div>
<div style="clear: both;"></div>
<div class="threadContent">_</div>
</div>
</div>
</div>
<div id="postReplyContainer" style="display: none;">
<hr/>
<div id="postReplyClose">
<i class="fa fa-times" aria-hidden="true"></i>
</div>
<div id="replyContentContainer">
<div class="alertBox">
<hr />
<div id="postReplyClose">
<i class="fa fa-times" aria-hidden="true"></i>
</div>
<div id="replyContentContainer">
<div class="alertBox">
</div>
<textarea placeholder="Reply content..." id="replyContentBox"></textarea>
<div id="submitReplyButton">
<i class="fa fa-reply" aria-hidden="true"></i>
</div>
</div>
<textarea placeholder="Reply content..." id="replyContentBox"></textarea>
<div id="submitReplyButton">
<i class="fa fa-reply" aria-hidden="true"></i>
</div>
</div>
</div>
<script>
@ -49,11 +54,14 @@ $.getJSON("_thread?id=" + parseGet('id'), function(Response) {
$('.threadStart .timePosted').html(getDate(Response.Thread.creationDate));
$('.threadStart .threadTitle').html(decodeURIComponent(Response.Thread.title));
$('.threadStart a.userProfileLink').attr("href", "user?id=" + Response.Thread.author.id);
$('.threadStart .threadContent').html(decodeURIComponent(Response.Thread.content));
$('.threadStart .threadContent').html(decodeURIComponent(Response.Thread.formattedContent));
if (Response.Thread.author.avatarURL != "")
$('.threadStart .userAvatar').html("").attr("style", "background-image:url('" + Response.Thread.author.avatarURL + "');'");
$('#replyThreadButton').attr("href", "postthread?threadid=" + Response.Thread.id);
if (user.user.id == Response.Thread.author.id)
$('#editThreadCaption').css("display", "block");
$.each(Response.Replies, function(i, eachReply) {
var cat = "<div class='threadStart table' style='width: 100%;'> \
@ -71,7 +79,8 @@ $.getJSON("_thread?id=" + parseGet('id'), function(Response) {
</div> \
<div class='threadInfo tableCell'> \
<i style=\"" + shouldHideAction(eachReply.author) + "\" replyid='" + eachReply.id + "' class=\"fa fa-times actionHover actionDelete\" aria-hidden=\"true\"></i> \
<div class='threadContent'>" + decodeURIComponent(eachReply.content) + "</div> \
<i style=\"" + shouldHideAction(eachReply.author) + "\" replyid='" + eachReply.id + "' class=\"fa fa-pencil-square-o actionHover actionEdit\" aria-hidden=\"true\"></i> \
<div class='threadContent'>" + decodeURIComponent(eachReply.formattedContent) + "</div> \
</div> \
</div>";
@ -94,6 +103,24 @@ $('#postReplyClose').click(function(e) {
$("#submitReplyButton").click(function(e) {
e.preventDefault();
if ($('#postReplyContainer').attr("editthread") == "true") {
$.getJSON("_editthread",
{
content : $('#replyContentBox').val(),
title : $('#postReplyContainer').attr("threadtitle"),
id : parseGet("id"),
update: true
},
function(result) {
if (result["errorCode"] == 0)
window.location.replace(result["destination"]);
else {
showErrorMessage(result["errorCode"]);
}
});
}
else if ($('#postReplyContainer').attr("editreply") != "true") {
$.getJSON("_postthread",
{
content : $('#replyContentBox').val(),
@ -108,6 +135,26 @@ $("#submitReplyButton").click(function(e) {
showErrorMessage(result["errorCode"]);
}
});
}
else {
$.getJSON("_editthread",
{
content : $('#replyContentBox').val(),
title : "Reply",
replyid : $('#postReplyContainer').attr("replyid"),
threadid : parseGet("id")
},
function(result) {
if (result["errorCode"] == 0)
window.location.replace(result["destination"]);
else {
showErrorMessage(result["errorCode"]);
}
});
}
});
@ -123,4 +170,40 @@ $('#content').on('click', '.actionDelete', function(e) {
});
});
$('#content').on('click', '.actionEdit', function (e) {
$('#postReplyContainer').slideDown('fast');
var id = $(this).attr("replyID")
$.getJSON("_thread?replyid=" + id, function(Response) {
$('#postReplyContainer').find("textarea").html(Response.content);
$('#postReplyContainer').attr("editReply", true);
$('#postReplyContainer').attr("replyid", id);
});
/*$.getJSON("_editthread",
{
replyid: $(this).attr("replyid"),
delete: false
},
function (response) {
if (response.success)
window.location.replace(response.destination);
});*/
});
$("#editThreadCaption").click(function(e) {
$('#postReplyContainer').slideDown('fast');
$.getJSON("_thread?id=" + parseGet("id"), function(Response) {
$('#postReplyContainer').find("textarea").html(Response.Thread.content);
$('#postReplyContainer').attr("editthread", true);
$('#postReplyContainer').attr("threadid", parseGet("id"));
$('#postReplyContainer').attr("threadtitle", Response.Thread.title);
});
});
</script>

View File

@ -2,50 +2,56 @@
</div>
<div id="userInfoBox">
<div class="table" style="width: 100%;">
<div class="tableCell" style="vertical-align:middle; width: 70%;">
<div class="userInfoField table">
<i class="fa fa-user tableCell" aria-hidden="true"></i> <span class="tableCell" id="userCreated">_</span>
</div>
<div class="table" style="width: 100%;">
<div class="tableCell" style="vertical-align:middle; width: 70%;">
<div class="userInfoField table">
<i class="fa fa-user tableCell" aria-hidden="true"></i> <span class="tableCell" id="userCreated">_</span>
</div>
<div class="userInfoField table">
<i class="fa fa-clock-o tableCell" aria-hidden="true"></i> <span class="tableCell" id="userLogon">_</span>
</div>
<div class="userInfoField table">
<i class="fa fa-clock-o tableCell" aria-hidden="true"></i> <span class="tableCell" id="userLogon">_</span>
</div>
<div class="userInfoField table">
<i class="fa fa-comment tableCell" aria-hidden="true"></i> <span class="tableCell" id="userPostCount">_</span>
</div>
<div class="userInfoField table">
<i class="fa fa-comment tableCell" aria-hidden="true"></i> <span class="tableCell" id="userPostCount">_</span>
</div>
<div class="userInfoField table">
<i class="fa fa-envelope-o tableCell" aria-hidden="true"></i> <span class="tableCell" id="userEmail"><a href="#" class="themeBlue">_</a></span>
</div>
<div class="userInfoField table">
<i class="fa fa-envelope-o tableCell" aria-hidden="true"></i> <span class="tableCell" id="userEmail"><a href="#" class="themeBlue">_</a></span>
</div>
<div class="userInfoField table">
<i class="fa fa-users tableCell" aria-hidden="true"></i> <span class="tableCell" id="userRank">_</span>
</div>
<div class="userInfoField table">
<i class="fa fa-users tableCell" aria-hidden="true"></i> <span class="tableCell" id="userRank">_</span>
</div>
</div>
<div class="tableCell" style="vertical-align:middle;">
<div id="userAvatar" class="">
<i class="fa fa-user-secret" aria-hidden="true" style="font-size: 19em; margin-top: -56px;"></i>
</div>
</div>
</div>
<div class="tableCell" style="vertical-align:middle;">
<div id="userAvatar" class="">
<i class="fa fa-user-secret" aria-hidden="true" style="font-size: 19em; margin-top: -56px;"></i>
</div>
</div>
</div>
<hr style="width: calc(100% + 2em); margin-bottom: -1em; margin-left: -1em;"/>
<hr style="width: calc(100% + 2em); margin-bottom: -1em; margin-left: -1em;" />
</div>
<div style="width: 100%; text-align: center; margin: 1em 0;"><a href="usercp">User Control Panel</a></div>
<script>
$.getJSON("_userinfo?id=" + parseGet('id'), function(user) {
$.getJSON("_userinfo?id=" + parseGet('id'), function (Response) {
var user = Response.user;
if (user == null)
return false;
$('#userCover').html(user.username);
$('#userCover').css("background-color", Response.profile.bannerColor);
var creationDate = new Date(user.creationDate);
$('#userCreated').html("Joined " + (creationDate.getMonth() + 1) + '-' + creationDate.getDate() + '-' + creationDate.getFullYear());
$('#userLogon').html("Last seen " + checkJustNow(user.lastLoginString));
$('#userLogon').html("Last seen " + user.lastLoginString);
$('#userPostCount').html(user.posts + " Posts");
$('#userEmail a').html(user.email);
$('#userEmail a').attr("href", "mailto:" + user.email);
if (Response.profile.showEmail) {
$('#userEmail a').html(user.email);
$('#userEmail a').attr("href", "mailto:" + user.email);
}
$('#userAvatar').html('');
$('#userAvatar').attr("style", "background-image:url('" + user.avatarURL + "');'");
$('#userRank').html(user.ranking.name);

View File

@ -0,0 +1,64 @@
<div class="alertBox">
</div>
<form id="userCP">
<div class="table">
<div class="tableCell">
<span style="display:flex; margin: 0.25em;">Username</span>
<input type="text" name="username" id="username" />
</div>
<div class="tableCell">
<span style="display:flex; margin: 0.25em;">Banner Color</span>
<input type="color" name="bannercolor" id="bannercolor" />
</div>
</div>
<div class="table">
<div class="tableCell">
<span style="display:flex; margin: 0.25em;">New Password</span>
<input type="password" name="updatedpassword" id="updatedpassword"/>
</div>
<div class="table">
<span style="display:flex; margin: 0.25em;">Repeat New Password</span>
<input type="password" name="updatedpasswordrepeat" id="updatedpasswordrepeat" />
</div>
</div>
<div id="userAvatar" style="margin: 1em 0;">
</div>
<span style="display:flex; margin: 0.25em;">Avatar URL</span>
<input style="width: 35%;" type="text" id="avatarurl" name="avatarurl" /><br />
<input id="updateprofile" type="submit" name="submit" value="Update" />
</form>
<script>
$.getJSON("_userinfo", function(result) {
$("#userAvatar").css('background-image', "".concat("url(", result.user['avatarURL'], ")"));
$("#username").val(result.user.username);
$("#bannercolor").val(result.profile.bannerColor);
$("#avatarurl").val(result.user.avatarURL);
});
$('#updateprofile').click(function (e) {
if (user.id == 0)
return false;
e.preventDefault();
$.getJSON("_updateuser",
{
username : $('#username').val(),
bannercolor : $('#bannercolor').val(),
avatarurl : $('#avatarurl').val(),
updatedpassword : $('#updatedpassword').val(),
updatedpasswordrepeat: $('#updatedpasswordrepeat').val()
},
function(result) {
if (result["errorCode"] == 0)
window.location.replace(result["destination"]);
else {
showErrorMessage(result["errorCode"]);
}
});
});
</script>

View File

@ -1,6 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CodeKicker.BBCode" version="5.0.0.0" targetFramework="net40" />
<package id="CryptSharp" version="1.2.0.1" targetFramework="net40" />
<package id="MarkdownDeep.NET" version="1.5" targetFramework="net40" />
<package id="DNA.Text" version="2.1.1.10633" targetFramework="net40" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net40" requireReinstallation="true" />
</packages>

View File

@ -69,7 +69,7 @@ namespace SharedLibrary.Commands
public override async Task ExecuteAsync(Event E)
{
E.Target.lastOffense = SharedLibrary.Utilities.RemoveWords(E.Data, 1);
E.Target.lastOffense = E.Data.RemoveWords(1);
if (E.Origin.Level > E.Target.Level)
await E.Target.Kick(E.Target.lastOffense, E.Origin);
else
@ -102,9 +102,9 @@ namespace SharedLibrary.Commands
}
}
class SBan : Command
class CBan : Command
{
public SBan(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CBan(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)
{
@ -125,9 +125,9 @@ namespace SharedLibrary.Commands
}
}
class Unban : Command
class CUnban : Command
{
public Unban(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CUnban(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)
{
@ -136,9 +136,9 @@ namespace SharedLibrary.Commands
}
}
class WhoAmI : Command
class CWhoAmI : Command
{
public WhoAmI(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CWhoAmI(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)
{
@ -147,9 +147,9 @@ namespace SharedLibrary.Commands
}
}
class List : Command
class CList : Command
{
public List(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CList(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)
{
@ -180,9 +180,9 @@ namespace SharedLibrary.Commands
}
}
class Help : Command
class CHelp : Command
{
public Help(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CHelp(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)
{
@ -230,9 +230,9 @@ namespace SharedLibrary.Commands
}
}
class FastRestart : Command
class CFastRestart : Command
{
public FastRestart(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CFastRestart(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)
{
@ -242,9 +242,9 @@ namespace SharedLibrary.Commands
}
}
class MapRotate : Command
class CMapRotate : Command
{
public MapRotate(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CMapRotate(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)
{
@ -254,24 +254,30 @@ namespace SharedLibrary.Commands
}
}
class SetLevel : Command
class CSetLevel : Command
{
public SetLevel(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CSetLevel(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
{
if (E.Target == E.Origin)
{
await E.Origin.Tell("You can't set your own level, silly.");
await E.Origin.Tell("You cannot change your own level.");
return;
}
Player.Permission newPerm = Utilities.matchPermission(Utilities.RemoveWords(E.Data, 1));
if (newPerm == Player.Permission.Owner && E.Origin.Level != Player.Permission.Console)
newPerm = Player.Permission.Banned;
bool playerInOtherServer = false;
if (newPerm > Player.Permission.Banned)
{
E.Target.setLevel(newPerm);
// prevent saving of old permissions on disconnect
// todo: manager DB
foreach (var server in E.Owner.Manager.GetServers())
{
foreach (var player in server.getPlayers())
@ -280,11 +286,13 @@ namespace SharedLibrary.Commands
{
player.setLevel(newPerm);
await E.Target.Tell("Congratulations! You have been promoted to ^3" + newPerm);
playerInOtherServer = true;
}
}
}
await E.Target.Tell("Congratulations! You have been promoted to ^3" + newPerm);
if (!playerInOtherServer)
await E.Target.Tell("Congratulations! You have been promoted to ^3" + newPerm);
await E.Origin.Tell(E.Target.Name + " was successfully promoted!");
//NEEED TO MOVE
@ -296,9 +304,9 @@ namespace SharedLibrary.Commands
}
}
class Usage : Command
class CUsage : Command
{
public Usage(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CUsage(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)
{
@ -306,9 +314,9 @@ namespace SharedLibrary.Commands
}
}
class Uptime : Command
class CUptime : Command
{
public Uptime(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CUptime(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)
{
@ -317,23 +325,24 @@ namespace SharedLibrary.Commands
}
}
class Admins : Command
class CListAdmins : Command
{
public Admins(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CListAdmins(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)
{
List<Player> activePlayers = E.Owner.getPlayers();
foreach (Player P in E.Owner.getPlayers())
for (int i = 0; i < E.Owner.Players.Count; i++)
{
var P = E.Owner.Players[i];
if (P != null && P.Level > Player.Permission.Flagged && !P.Masked)
await E.Origin.Tell(String.Format("[^3{0}^7] {1}", Utilities.levelToColor(P.Level), P.Name));
}
}
}
class MapCMD : Command
class CLoadMap : Command
{
public MapCMD(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CLoadMap(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)
{
@ -355,9 +364,9 @@ namespace SharedLibrary.Commands
}
}
class Find : Command
class CFindPlayer : Command
{
public Find(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CFindPlayer(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)
{
@ -377,9 +386,9 @@ namespace SharedLibrary.Commands
}
}
class FindAll : Command
class CFindAllPlayers : Command
{
public FindAll(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CFindAllPlayers(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)
{
@ -424,14 +433,14 @@ namespace SharedLibrary.Commands
}
}
class Rules : Command
class CListRules : Command
{
public Rules(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CListRules(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
{
if (E.Owner.rules.Count < 1)
await E.Origin.Tell("This server has not set any rules.");
await E.Origin.Tell("The server onwer has not set any rules.");
else
{
foreach (String r in E.Owner.rules)
@ -440,9 +449,9 @@ namespace SharedLibrary.Commands
}
}
class PrivateMessage : Command
class CPrivateMessage : Command
{
public PrivateMessage(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CPrivateMessage(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)
{
@ -452,9 +461,9 @@ namespace SharedLibrary.Commands
}
}
class Reload : Command
class CReload : Command
{
public Reload(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CReload(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)
{
@ -465,26 +474,6 @@ namespace SharedLibrary.Commands
}
}
class Balance : Command
{
public Balance(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
{
await E.Owner.ExecuteCommandAsync(String.Format("admin_lastevent {0};{1}", "balance", E.Origin.npID)); //Let gsc do the magic
}
}
class GoTo : Command
{
public GoTo(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
{
await E.Owner.ExecuteCommandAsync(String.Format("admin_lastevent {0};{1};{2};{3}", "goto", E.Origin.npID, E.Target.Name, E.Data)); //Let gsc do the magic
}
}
class Flag : Command
{
public Flag(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
@ -513,9 +502,9 @@ namespace SharedLibrary.Commands
}
}
class _Report : Command
class CReport : Command
{
public _Report(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CReport(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)
{
@ -527,7 +516,7 @@ namespace SharedLibrary.Commands
if (E.Target == E.Origin)
{
await E.Origin.Tell("You cannot report yourself, silly.");
await E.Origin.Tell("You cannot report yourself.");
return;
}
@ -537,7 +526,7 @@ namespace SharedLibrary.Commands
return;
}
E.Data = Utilities.RemoveWords(E.Data, 1);
E.Data = E.Data.RemoveWords(1);
E.Owner.Reports.Add(new Report(E.Target, E.Origin, E.Data));
await E.Origin.Tell("Successfully reported " + E.Target.Name);
@ -547,9 +536,9 @@ namespace SharedLibrary.Commands
}
}
class Reports : Command
class CListReports : Command
{
public Reports(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CListReports(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)
{
@ -571,20 +560,9 @@ namespace SharedLibrary.Commands
}
}
class _Tell : Command
class CMask : Command
{
public _Tell(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)
{
E.Data = Utilities.RemoveWords(E.Data, 1);
await E.Owner.ExecuteCommandAsync(String.Format("admin_lastevent tell;{0};{1};{2}", E.Origin.npID, E.Target.npID, E.Data));
}
}
class Mask : Command
{
public Mask(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CMask(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)
{
@ -601,9 +579,9 @@ namespace SharedLibrary.Commands
}
}
class BanInfo : Command
class CListBanInfo : Command
{
public BanInfo(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CListBanInfo(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)
{
@ -633,9 +611,9 @@ namespace SharedLibrary.Commands
}
}
class Alias : Command
class CListAlias : Command
{
public Alias(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CListAlias(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)
{
@ -684,9 +662,9 @@ namespace SharedLibrary.Commands
}
}
class _RCON : Command
class CExecuteRCON : Command
{
public _RCON(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public CExecuteRCON(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)
{
@ -694,28 +672,5 @@ namespace SharedLibrary.Commands
await E.Origin.Tell("Successfuly sent RCON command!");
}
}
class Link : Command
{
public Link(String N, String D, String U, Player.Permission P, int args, bool nT) : base(N, D, U, P, args, nT) { }
public override async Task ExecuteAsync(Event E)
{
if (E.Data.Contains("show"))
{
if (E.Origin.UID == null || E.Origin.UID.Length == 0)
await E.Origin.Tell("You have not linked an ID");
else
await E.Origin.Tell("Your ID is " + E.Origin.UID);
}
else if (E.Origin.registerUID(E.Data))
{
E.Owner.clientDB.updatePlayer(E.Origin);
await E.Origin.Tell("Your ID has been linked");
}
else
await E.Origin.Tell("That ID is invalid");
}
}
}

View File

@ -18,13 +18,13 @@ namespace SharedLibrary
Con = new SQLiteConnection(DBCon);
}
catch(DllNotFoundException)
catch (DllNotFoundException)
{
Console.WriteLine("Fatal Error: could not locate the SQLite DLL(s)!\nEnsure they are located in the 'lib' folder");
Utilities.Wait(5);
Environment.Exit(0);
}
Open = false;
Init();
}
@ -114,7 +114,7 @@ namespace SharedLibrary
{
waitForClose();
int rowsUpdated = 0;
Request = Request.Replace("!'", "").Replace("!", "") ;
Request = Request.Replace("!'", "").Replace("!", "");
try
{
lock (Con)
@ -134,7 +134,7 @@ namespace SharedLibrary
Console.WriteLine(E.StackTrace);
Console.WriteLine(Request);
return 0;
}
}
}
protected DataTable GetDataTable(string tableName, KeyValuePair<string, object> where)
@ -154,6 +154,27 @@ namespace SharedLibrary
Con.Close();
}
catch (Exception e)
{
//LOGME
Console.Write("Could not execute");
}
return dt;
}
protected DataTable GetDataTable(SQLiteCommand cmd)
{
DataTable dt = new DataTable();
try
{
Con.Open();
SQLiteDataReader reader = cmd.ExecuteReader();
dt.Load(reader);
reader.Close();
Con.Close();
}
catch (Exception e)
{
//LOGME
@ -166,7 +187,7 @@ namespace SharedLibrary
protected DataTable GetDataTable(String sql)
{
DataTable dt = new DataTable();
try
{
waitForClose();
@ -214,7 +235,7 @@ namespace SharedLibrary
{
if (!File.Exists(FileName))
{
String Create = "CREATE TABLE [CLIENTS] ( [Name] TEXT NULL, [npID] TEXT NULL, [Number] INTEGER PRIMARY KEY AUTOINCREMENT, [Level] INT DEFAULT 0 NULL, [LastOffense] TEXT NULL, [Connections] INT DEFAULT 1 NULL, [IP] TEXT NULL, [LastConnection] TEXT NULL, [UID] TEXT NULL, [Masked] INT DEFAULT 0);";
String Create = "CREATE TABLE [CLIENTS] ( [Name] TEXT NULL, [npID] TEXT NULL, [Number] INTEGER PRIMARY KEY AUTOINCREMENT, [Level] INT DEFAULT 0 NULL, [LastOffense] TEXT NULL, [Connections] INT DEFAULT 1 NULL, [IP] TEXT NULL, [LastConnection] TEXT NULL, [UID] TEXT NULL, [Masked] INT DEFAULT 0, [Reserved] INT DEFAULT 0);";
ExecuteNonQuery(Create);
Create = "CREATE TABLE [BANS] ( [TYPE] TEXT NULL, [Reason] TEXT NULL, [npID] TEXT NULL, [bannedByID] TEXT NULL, [IP] TEXT NULL, [TIME] TEXT NULL);";
ExecuteNonQuery(Create);
@ -224,8 +245,7 @@ namespace SharedLibrary
//Returns a single player object with matching GUID, false if no matches
public Player getPlayer(String ID, int cNum)
{
String Query = String.Format("SELECT * FROM CLIENTS WHERE npID = '{0}' LIMIT 1", ID);
DataTable Result = GetDataTable(Query);
DataTable Result = GetDataTable("CLIENTS", new KeyValuePair<string, object>("npID", ID));
if (Result != null && Result.Rows.Count > 0)
{
@ -243,7 +263,7 @@ namespace SharedLibrary
public List<Player> getRecentPlayers()
{
List<Player> returnssss = new List<Player>();
String Query = String.Format("SELECT * FROM CLIENTS ORDER BY LastConnection desc LIMIT 25");
String Query = String.Format("SELECT * FROM CLIENTS ORDER BY Connections desc LIMIT 25");
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
@ -260,11 +280,27 @@ namespace SharedLibrary
return returnssss;
}
public List<string> getReservedNPIDs()
{
List<string> npIDs = new List<string>();
String Query = String.Format("SELECT npID FROM CLIENTS WHERE Reserved = 1");
DataTable Result = GetDataTable(Query);
if (Result != null && Result.Rows.Count > 0)
foreach (DataRow ResponseRow in Result.Rows)
npIDs.Add(ResponseRow["npID"].ToString());
return npIDs;
}
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);
@ -307,8 +343,7 @@ namespace SharedLibrary
//Overloaded method for getPlayer, returns Client with matching DBIndex, null if none found
public Player getPlayer(int dbIndex)
{
String Query = String.Format("SELECT * FROM CLIENTS WHERE Number = '{0}' LIMIT 1", dbIndex);
DataTable Result = GetDataTable(Query);
DataTable Result = GetDataTable("CLIENTS", new KeyValuePair<string, object>("Number", dbIndex));
if (Result != null && Result.Rows.Count > 0)
{
@ -333,8 +368,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);
DataTable Result = GetDataTable(Query);
DataTable Result = GetDataTable("CLIENTS", new KeyValuePair<string, object>("IP", IP));
if (Result != null && Result.Rows.Count > 0)
{
@ -371,9 +405,11 @@ namespace SharedLibrary
//Returns a list of players matching name parameter, null if no players found matching
public List<Player> findPlayers(String name)
{
name = name.Replace("'", "");
String Query = String.Format("SELECT * FROM CLIENTS WHERE Name LIKE '%{0}%' LIMIT 32", name);
DataTable Result = GetDataTable(Query);
SQLiteCommand cmd = new SQLiteCommand(Con);
cmd.CommandText = "SELECT * FROM CLIENTS WHERE Name LIKE @Name LIMIT 32";
cmd.Parameters.AddWithValue("@Name", '%' + name + '%');
var Result = GetDataTable(cmd);
List<Player> Players = new List<Player>();
@ -439,7 +475,7 @@ namespace SharedLibrary
BanType = (Penalty.Type)Enum.Parse(typeof(Penalty.Type), Row["TYPE"].ToString());
Bans.Add(new Penalty(BanType, Row["Reason"].ToString().Trim(), Row["npID"].ToString(), Row["bannedByID"].ToString(), DateTime.Parse(Row["TIME"].ToString()), Row["IP"].ToString()));
}
return Bans;
@ -501,7 +537,7 @@ namespace SharedLibrary
updatedPlayer.Add("UID", P.UID);
updatedPlayer.Add("Masked", Convert.ToInt32(P.Masked));
Update("CLIENTS", updatedPlayer, new KeyValuePair<string, object>("npID", P.npID ));
Update("CLIENTS", updatedPlayer, new KeyValuePair<string, object>("npID", P.npID));
}
@ -530,7 +566,7 @@ namespace SharedLibrary
public void removeBan(String GUID, String IP)
{
String Query = String.Format("DELETE FROM BANS WHERE npID = '{0}' or IP= '%{1}%'", GUID, IP);
String Query = String.Format("DELETE FROM BANS WHERE npID = '{0}' or IP = '{1}'", GUID, IP);
ExecuteNonQuery(Query);
}
}
@ -565,8 +601,12 @@ namespace SharedLibrary
public List<Aliases> getPlayer(String IP)
{
String Query = String.Format("SELECT * FROM ALIASES WHERE IPS LIKE '%{0}%'", IP);
DataTable Result = GetDataTable(Query);
SQLiteCommand cmd = new SQLiteCommand(Con);
cmd.CommandText = "SELECT * FROM ALIASES WHERE IPS LIKE @IP";
cmd.Parameters.AddWithValue("@IP", IP);
var Result = GetDataTable(cmd);
List<Aliases> players = new List<Aliases>();
if (Result != null && Result.Rows.Count > 0)
@ -586,8 +626,13 @@ namespace SharedLibrary
if (EyePee.Length > 1)
Penor = (EyePee[0] + '.' + EyePee[1] + '.');
String Query = String.Format("SELECT * FROM ALIASES WHERE NAMES LIKE '%{0}%' OR IPS LIKE '%{1}%' LIMIT 15", name, Penor);
DataTable Result = GetDataTable(Query);
SQLiteCommand cmd = new SQLiteCommand(Con);
cmd.CommandText = "SELECT * FROM ALIASES WHERE NAMES LIKE @name OR IPS LIKE @ip LIMIT 15";
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@ip", Penor);
var Result = GetDataTable(cmd);
List<Aliases> players = new List<Aliases>();

View File

@ -1,7 +1,7 @@
using System;
using System.Threading.Tasks;
namespace SharedLibrary.Extensions
namespace SharedLibrary.Interfaces
{
public interface IPlugin
{

View File

@ -47,7 +47,7 @@ namespace SharedLibrary.Network
static string[] SendQuery(QueryType Type, Server QueryServer, string Parameters = "")
{
var ServerOOBConnection = new System.Net.Sockets.UdpClient();
var ServerOOBConnection = new UdpClient();
ServerOOBConnection.Client.SendTimeout = 1000;
ServerOOBConnection.Client.ReceiveTimeout = 1000;
var Endpoint = new IPEndPoint(IPAddress.Parse(QueryServer.getIP()), QueryServer.getPort());
@ -72,7 +72,6 @@ namespace SharedLibrary.Network
try
{
ServerOOBConnection.Connect(Endpoint);
ServerOOBConnection.Send(Payload, Payload.Length);

View File

@ -56,32 +56,31 @@ namespace SharedLibrary
commands.Add(new Kick("kick", "kick a player by name. syntax: !kick <player> <reason>.", "k", Player.Permission.Trusted, 2, true));
commands.Add(new Say("say", "broadcast message to all players. syntax: !say <message>.", "s", Player.Permission.Moderator, 1, false));
commands.Add(new TempBan("tempban", "temporarily ban a player for 1 hour. syntax: !tempban <player> <reason>.", "tb", Player.Permission.Moderator, 2, true));
commands.Add(new SBan("ban", "permanently ban a player from the server. syntax: !ban <player> <reason>", "b", Player.Permission.SeniorAdmin, 2, true));
commands.Add(new WhoAmI("whoami", "give information about yourself. syntax: !whoami.", "who", Player.Permission.User, 0, false));
commands.Add(new List("list", "list active clients syntax: !list.", "l", Player.Permission.Moderator, 0, false));
commands.Add(new Help("help", "list all available commands. syntax: !help.", "h", Player.Permission.User, 0, false));
commands.Add(new FastRestart("fastrestart", "fast restart current map. syntax: !fastrestart.", "fr", Player.Permission.Moderator, 0, false));
commands.Add(new MapRotate("maprotate", "cycle to the next map in rotation. syntax: !maprotate.", "mr", Player.Permission.Administrator, 0, false));
commands.Add(new SetLevel("setlevel", "set player to specified administration level. syntax: !setlevel <player> <level>.", "sl", Player.Permission.Owner, 2, true));
commands.Add(new Usage("usage", "get current application memory usage. syntax: !usage.", "us", Player.Permission.Moderator, 0, false));
commands.Add(new Uptime("uptime", "get current application running time. syntax: !uptime.", "up", Player.Permission.Moderator, 0, false));
commands.Add(new CBan("ban", "permanently ban a player from the server. syntax: !ban <player> <reason>", "b", Player.Permission.SeniorAdmin, 2, true));
commands.Add(new CWhoAmI("whoami", "give information about yourself. syntax: !whoami.", "who", Player.Permission.User, 0, false));
commands.Add(new CList("list", "list active clients syntax: !list.", "l", Player.Permission.Moderator, 0, false));
commands.Add(new CHelp("help", "list all available commands. syntax: !help.", "h", Player.Permission.User, 0, false));
commands.Add(new CFastRestart("fastrestart", "fast restart current map. syntax: !fastrestart.", "fr", Player.Permission.Moderator, 0, false));
commands.Add(new CMapRotate("maprotate", "cycle to the next map in rotation. syntax: !maprotate.", "mr", Player.Permission.Administrator, 0, false));
commands.Add(new CSetLevel("setlevel", "set player to specified administration level. syntax: !setlevel <player> <level>.", "sl", Player.Permission.Owner, 2, true));
commands.Add(new CUsage("usage", "get current application memory usage. syntax: !usage.", "us", Player.Permission.Moderator, 0, false));
commands.Add(new CUptime("uptime", "get current application running time. syntax: !uptime.", "up", Player.Permission.Moderator, 0, false));
commands.Add(new Warn("warn", "warn player for infringing rules syntax: !warn <player> <reason>.", "w", Player.Permission.Trusted, 2, true));
commands.Add(new WarnClear("warnclear", "remove all warning for a player syntax: !warnclear <player>.", "wc", Player.Permission.Trusted, 1, true));
commands.Add(new Unban("unban", "unban player by database id. syntax: !unban @<id>.", "ub", Player.Permission.SeniorAdmin, 1, true));
commands.Add(new Admins("admins", "list currently connected admins. syntax: !admins.", "a", Player.Permission.User, 0, false));
commands.Add(new MapCMD("map", "change to specified map. syntax: !map", "m", Player.Permission.Administrator, 1, false));
commands.Add(new Find("find", "find player in database. syntax: !find <player>", "f", Player.Permission.SeniorAdmin, 1, false));
commands.Add(new Rules("rules", "list server rules. syntax: !rules", "r", Player.Permission.User, 0, false));
commands.Add(new PrivateMessage("privatemessage", "send message to other player. syntax: !pm <player> <message>", "pm", Player.Permission.User, 2, true));
commands.Add(new CUnban("unban", "unban player by database id. syntax: !unban @<id>.", "ub", Player.Permission.SeniorAdmin, 1, true));
commands.Add(new CListAdmins("admins", "list currently connected admins. syntax: !admins.", "a", Player.Permission.User, 0, false));
commands.Add(new CLoadMap("map", "change to specified map. syntax: !map", "m", Player.Permission.Administrator, 1, false));
commands.Add(new CFindPlayer("find", "find player in database. syntax: !find <player>", "f", Player.Permission.SeniorAdmin, 1, false));
commands.Add(new CListRules("rules", "list server rules. syntax: !rules", "r", Player.Permission.User, 0, false));
commands.Add(new CPrivateMessage("privatemessage", "send message to other player. syntax: !pm <player> <message>", "pm", Player.Permission.User, 2, true));
commands.Add(new Flag("flag", "flag a suspicious player and announce to admins on join . syntax !flag <player>:", "flag", Player.Permission.Moderator, 1, true));
commands.Add(new _Report("report", "report a player for suspicious behaivor. syntax !report <player> <reason>", "rep", Player.Permission.User, 2, true));
commands.Add(new Reports("reports", "get most recent reports. syntax !reports", "reports", Player.Permission.Moderator, 0, false));
commands.Add(new _Tell("tell", "send onscreen message to player. syntax !tell <player> <message>", "t", Player.Permission.Moderator, 2, true));
commands.Add(new Mask("mask", "hide your online presence from online admin list. syntax: !mask", "mask", Player.Permission.Administrator, 0, false));
commands.Add(new BanInfo("baninfo", "get information about a ban for a player. syntax: !baninfo <player>", "bi", Player.Permission.Moderator, 1, true));
commands.Add(new Alias("alias", "get past aliases and ips of a player. syntax: !alias <player>", "known", Player.Permission.Moderator, 1, true));
commands.Add(new _RCON("rcon", "send rcon command to server. syntax: !rcon <command>", "rcon", Player.Permission.Owner, 1, false));
commands.Add(new FindAll("findall", "find a player by their aliase(s). syntax: !findall <player>", "fa", Player.Permission.Moderator, 1, false));
commands.Add(new CReport("report", "report a player for suspicious behaivor. syntax !report <player> <reason>", "rep", Player.Permission.User, 2, true));
commands.Add(new CListReports("reports", "get most recent reports. syntax !reports", "reports", Player.Permission.Moderator, 0, false));
commands.Add(new CMask("mask", "hide your online presence from online admin list. syntax: !mask", "mask", Player.Permission.Administrator, 0, false));
commands.Add(new CListBanInfo("baninfo", "get information about a ban for a player. syntax: !baninfo <player>", "bi", Player.Permission.Moderator, 1, true));
commands.Add(new CListAlias("alias", "get past aliases and ips of a player. syntax: !alias <player>", "known", Player.Permission.Moderator, 1, true));
commands.Add(new CExecuteRCON("rcon", "send rcon command to server. syntax: !rcon <command>", "rcon", Player.Permission.Owner, 1, false));
commands.Add(new CFindAllPlayers("findall", "find a player by their aliase(s). syntax: !findall <player>", "fa", Player.Permission.Moderator, 1, false));
}
//Returns the current server name -- *STRING*

View File

@ -71,7 +71,7 @@
<Compile Include="Map.cs" />
<Compile Include="Miscellaneous.cs" />
<Compile Include="Player.cs" />
<Compile Include="Extensions\IPlugin.cs" />
<Compile Include="Interfaces\IPlugin.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RCON.cs" />
<Compile Include="Report.cs" />

View File

@ -1,18 +1,17 @@
using System;
using SharedLibrary;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Data;
using SharedLibrary.Extensions;
using System.Threading.Tasks;
using SharedLibrary;
namespace StatsPlugin
{
public class StatCommand : Command
public class CViewStats : Command
{
public StatCommand() : base("stats", "view your stats. syntax !stats", "xlrstats", Player.Permission.User, 0, false) { }
public CViewStats() : base("stats", "view your stats. syntax !stats", "xlrstats", Player.Permission.User, 0, false) { }
public override async Task ExecuteAsync(Event E)
{
@ -35,9 +34,9 @@ namespace StatsPlugin
}
}
public class TopStats : Command
public class CViewTopStats : Command
{
public TopStats() : base("topstats", "view the top 5 players on this server. syntax !topstats", "!ts", Player.Permission.User, 0, false) { }
public CViewTopStats() : base("topstats", "view the top 5 players on this server. syntax !topstats", "!ts", Player.Permission.User, 0, false) { }
public override async Task ExecuteAsync(Event E)
{
@ -59,7 +58,7 @@ namespace StatsPlugin
/// Each server runs from the same plugin ( for easier reloading and reduced memory usage ).
/// So, to have multiple stat tracking, we must store a stat struct for each server
/// </summary>
public class Stats : IPlugin
public class Stats : SharedLibrary.Interfaces.IPlugin
{
public static List<StatTracking> statLists;
@ -72,7 +71,7 @@ namespace StatsPlugin
public StatTracking(int port)
{
playerStats = new StatsDB("Database/stats_" + port + ".rm");
playerStats = new StatsDB("stats_" + port + ".rm");
inactiveMinutes = new int[18];
Kills = new int[18];
deathStreaks = new int[18];
@ -101,18 +100,16 @@ namespace StatsPlugin
public async Task OnLoad()
{
statLists = new List<StatTracking>();
await Task.Delay(0);
}
public async Task OnUnload()
{
statLists.Clear();
await Task.Delay(0);
}
public async Task OnTick(Server S)
{
await Task.Delay(0);
return;
}
public async Task OnEvent(Event E, Server S)
@ -324,8 +321,7 @@ namespace StatsPlugin
public PlayerStats getStats(Player P)
{
String Query = String.Format("SELECT * FROM STATS WHERE npID = '{0}'", P.npID);
DataTable Result = GetDataTable(Query);
DataTable Result = GetDataTable("STATS", new KeyValuePair<string, object>("npID", P.npID));
if (Result != null && Result.Rows.Count > 0)
{

View File

@ -35,6 +35,9 @@
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite">
<HintPath>..\SharedLibrary\bin\Release\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
using SharedLibrary;
using SharedLibrary.Network;
using SharedLibrary.Extensions;
using SharedLibrary.Interfaces;
using System.Threading.Tasks;
namespace Votemap_Plugin

View File

@ -1,6 +1,6 @@
using System;
using SharedLibrary;
using SharedLibrary.Extensions;
using SharedLibrary.Interfaces;
using System.Threading.Tasks;
namespace Welcome_Plugin