diff --git a/AdminToolbox/AdminToolbox/API/ATWeb.cs b/AdminToolbox/AdminToolbox/API/ATWeb.cs
index 2bb4e63..ce4e9ed 100644
--- a/AdminToolbox/AdminToolbox/API/ATWeb.cs
+++ b/AdminToolbox/AdminToolbox/API/ATWeb.cs
@@ -15,11 +15,14 @@ public static class ATWeb
private static AdminToolbox Plugin => AdminToolbox.singleton;
private static void Debug(string str) => Plugin.Debug("[ATWeb]: " + str);
+ private static void Info(string str) => Plugin.Info("[ATWeb]: " + str);
+
+ private const string ApiURL = "https://api.github.com/repos/Rnen/AdminToolbox/releases/latest";
///
/// Class for storing the latest GitHub release info
///
- public class AT_LatestReleaseInfo
+ public struct ATReleaseInfo
{
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
public string Title { get; }
@@ -27,7 +30,7 @@ public class AT_LatestReleaseInfo
public string Author { get; }
public string DownloadLink { get; }
- public AT_LatestReleaseInfo(string Title, string Version, string Author, string DownloadLink)
+ public ATReleaseInfo(string Title, string Version, string Author, string DownloadLink)
{
this.Title = Title;
this.Version = Version;
@@ -37,24 +40,43 @@ public AT_LatestReleaseInfo(string Title, string Version, string Author, string
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
+ private static DateTime _lastVersionCheck = DateTime.UtcNow;
+ private static ATReleaseInfo _latestReleaseInfo = new ATReleaseInfo();
+
///
- /// Returns a class containing info about the latest GitHub release
+ /// Returns a class containing info about the latest GitHub release
///
- public static AT_LatestReleaseInfo GetOnlineInfo(AdminToolbox plugin)
+ /// Only updates every 5 minutes to avoid rate limits
+ public static ATReleaseInfo LatestRelease
+ {
+ get
+ {
+ if (_lastVersionCheck.AddMinutes(5) < DateTime.UtcNow || _latestReleaseInfo.Equals(default(ATReleaseInfo)))
+ {
+ _latestReleaseInfo = GetOnlineInfo();
+ _lastVersionCheck = DateTime.UtcNow;
+ Debug("Refreshed online version!");
+ }
+ return _latestReleaseInfo;
+ }
+ }
+
+ private static ATReleaseInfo GetOnlineInfo()
{
+ Smod2.Attributes.PluginDetails Details = AdminToolbox.singleton.Details;
if (ConfigManager.Manager.Config.GetBoolValue("atb_disable_networking", false)
- || ConfigManager.Manager.Config.GetBoolValue("admintoolbox_disable_networking", false)) return new AT_LatestReleaseInfo(plugin.Details.name, plugin.Details.version, plugin.Details.author, "");
+ || ConfigManager.Manager.Config.GetBoolValue("admintoolbox_disable_networking", false))
+ return new ATReleaseInfo(Details.name, Details.version, Details.author, "");
string rawResponse = string.Empty;
- string apiURL = "https://api.github.com/repos/Rnen/AdminToolbox/releases/latest";
string _title = "", _version = "", _author = "", _dllink = "";
try
{
- using (UnityWebRequest ww = UnityWebRequest.Get(apiURL))
+ using (UnityWebRequest ww = UnityWebRequest.Get(ApiURL))
{
ww.SendWebRequest();
- DateTime timer = DateTime.Now.AddSeconds(2);
- while (!ww.isDone || (!ww.downloadHandler.isDone && DateTime.Now < timer)) { }
+ DateTime timer = DateTime.UtcNow.AddSeconds(2);
+ while (!ww.isDone || (!ww.downloadHandler.isDone && DateTime.UtcNow < timer)) { }
rawResponse = ww.downloadHandler.text;
if (string.IsNullOrEmpty(rawResponse))
throw new Exception("[AdminToolbox]: GitHub web request response was NullOrEmpty!");
@@ -76,17 +98,17 @@ string FindValue(string key)
catch (Exception e)
{
Debug("Exception: " + e.Message);
- plugin.Info(" \n\n - Downloading online version failed, skipping..." + "\n \n");
- return new AT_LatestReleaseInfo(plugin.Details.name, plugin.Details.version, plugin.Details.author, "");
+ Info(" \n\n - Downloading online version failed, skipping..." + "\n \n");
+ return new ATReleaseInfo(Details.name, Details.version, Details.author, "");
}
- return new AT_LatestReleaseInfo(_title, _version, _author, _dllink);
+ return new ATReleaseInfo(_title, _version, _author, _dllink);
}
internal static bool NewerVersionAvailable()
{
if (Plugin == null) return false;
string thisVersion = Plugin.Details.version.Split('-').FirstOrDefault().Replace(".", string.Empty);
- string onlineVersion = Plugin.GetGitReleaseInfo().Version.Split('-').FirstOrDefault().Replace(".", string.Empty);
+ string onlineVersion = LatestRelease.Version.Split('-').FirstOrDefault().Replace(".", string.Empty);
if (int.TryParse(thisVersion, out int thisV)
&& int.TryParse(onlineVersion, out int onlineV)
@@ -99,20 +121,20 @@ internal static string SendWebhook(DiscordWebhook discordWebHook, string url)
{
if (!string.IsNullOrEmpty(url) && Uri.TryCreate(url, UriKind.Absolute, out Uri uri))
{
- //string jsonData = UnityEngine.JsonUtility.ToJson(discordWebHook, true);
- string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(discordWebHook);
+ byte[] jsonData = Utf8Json.JsonSerializer.Serialize(discordWebHook);
+ Debug("WebHook sent: \n" + Utf8.GetString(jsonData));
return WebPost(uri, jsonData);
}
else
return "Failed creating URI of WebHook link: " + url;
}
- private static string WebPost(Uri uri, string rawJsonData)
+ private static string WebPost(Uri uri, byte[] rawJsonData)
{
using (WebClient wb = new WebClient())
{
wb.Headers[HttpRequestHeader.ContentType] = "application/json";
- return wb.UploadString(uri, "POST", rawJsonData);
+ return Utf8Json.JsonSerializer.PrettyPrint(wb.UploadData(uri, "POST", rawJsonData));
}
}
}
diff --git a/AdminToolbox/AdminToolbox/API/DiscordWebhook.cs b/AdminToolbox/AdminToolbox/API/DiscordWebhook.cs
index ced6225..0fdd422 100644
--- a/AdminToolbox/AdminToolbox/API/DiscordWebhook.cs
+++ b/AdminToolbox/AdminToolbox/API/DiscordWebhook.cs
@@ -1,21 +1,20 @@
namespace AdminToolbox.API.Webhook
{
- public class Image
+ public struct Image
{
public string url;
}
- public class Author
+ public struct Author
{
- public string name = "";
- public string url = "";
- public string icon_url = "";
+ public string name;
+ public string url;
+ public string icon_url;
}
- public class Field
+ public struct Field
{
public string name;
public string value;
- public string inline = "false";
- public Field() { }
+ public bool inline;
public Field(Field field)
{
@@ -24,10 +23,7 @@ public Field(Field field)
this.inline = field.inline;
}
- public override string ToString()
- {
- return "Name: " + this.name + " Value: " + this.value + " InLine: " + inline;
- }
+ public override string ToString() => "Name: " + this.name + " Value: " + this.value + " InLine: " + inline;
}
public class EmbedData
{
@@ -44,7 +40,7 @@ public class EmbedData
public class DiscordWebhook
{
public string username = "AdminToolbox";
- public string avatar_url = "https://puu.sh/D0DRU.png";
+ public string avatar_url = "https://i.imgur.com/nQpIuUT.png";
public string content = "";
public EmbedData[] embeds = new EmbedData[1] { new EmbedData() };
}
diff --git a/AdminToolbox/AdminToolbox/API/ExtentionMethods.cs b/AdminToolbox/AdminToolbox/API/ExtentionMethods.cs
index 8f79820..607efd3 100644
--- a/AdminToolbox/AdminToolbox/API/ExtentionMethods.cs
+++ b/AdminToolbox/AdminToolbox/API/ExtentionMethods.cs
@@ -4,6 +4,7 @@
using Smod2;
using Smod2.API;
using Smod2.Commands;
+using System.Reflection;
namespace AdminToolbox.API.Extentions
{
@@ -13,29 +14,25 @@ public static class ExtentionMethods
{
private static Server Server => PluginManager.Manager.Server;
- private static AdminToolbox Plugin => AdminToolbox.singleton;
-
internal static bool GetIsJailed(this Player player)
- => AdminToolbox.ATPlayerDict.ContainsKey(player.UserId) && AdminToolbox.ATPlayerDict[player.UserId].isJailed;
+ => AdminToolbox.ATPlayerDict.ContainsKey(player.UserID) && AdminToolbox.ATPlayerDict[player.UserID].isJailed;
public static bool IsInsideJail(this Player player)
{
Vector
jail = JailHandler.JailPos,
playerPos = player.GetPosition();
- float
- x = Math.Abs(playerPos.x - jail.x),
- y = Math.Abs(playerPos.y - jail.y),
- z = Math.Abs(playerPos.z - jail.z);
- return x > 7 || y > 5 || z > 7 ? false : true;
+ return Math.Abs(playerPos.x - jail.x) <= 7
+ && Math.Abs(playerPos.y - jail.y) <= 5
+ && Math.Abs(playerPos.z - jail.z) <= 7;
}
- internal static string[] UserIdsToArray(this List players)
+ internal static string[] UserIDsToArray(this List players)
{
string[] newArray = new string[players.Count];
for (int i = 0; i < players.Count; i++)
{
- newArray[i] = players[i].UserId;
+ newArray[i] = players[i].UserID;
}
return newArray;
}
@@ -49,8 +46,8 @@ internal static Player[] JailedPlayers(this Player[] players)
return players.Length > 0 && Server.Round.Duration > 0
? players
- .Where(p => p.TeamRole.Role != Smod2.API.RoleType.UNASSIGNED
- && p.TeamRole.Role != Smod2.API.RoleType.SPECTATOR
+ .Where(p => p.PlayerRole.RoleID != Smod2.API.RoleType.NONE
+ && p.PlayerRole.RoleID != Smod2.API.RoleType.SPECTATOR
&& !p.OverwatchMode
&& p.GetIsJailed()).ToArray()
: (new Player[0]);
@@ -58,7 +55,7 @@ internal static Player[] JailedPlayers(this Player[] players)
internal static List AddField(this List list, string title, string content, bool inline = false)
{
- list.Add(new Field { name = title, value = content, inline = inline ? "true" : "false" });
+ list.Add(new Field { name = title, value = content, inline = inline });
return list;
}
@@ -70,13 +67,13 @@ private static bool ContainsPlayer(this string[] array, Player player)
{
if (string.IsNullOrEmpty(str))
continue;
- if (str == player.UserId)
+ if (str == player.UserID)
return true;
- else if (player.GetUserGroup().Name != null && str == player.GetUserGroup().Name.Trim().ToUpper())
+ else if (player.GetUserGroup()?.Name != null && str == player.GetUserGroup()?.Name.Trim().ToUpper())
return true;
- else if (player.GetUserGroup().BadgeText != null && str == player.GetUserGroup().BadgeText.Trim().ToUpper())
+ else if (player.GetUserGroup()?.BadgeText != null && str == player.GetUserGroup()?.BadgeText.Trim().ToUpper())
return true;
- else if (player.GetRankName() != null && str == player.GetRankName().Trim().ToUpper())
+ else if (player.GetRankName() != null && str == player.GetRankName()?.Trim().ToUpper())
return true;
}
return false;
@@ -87,60 +84,70 @@ private static bool ContainsPlayer(this string[] array, Player player)
}
}
- internal static bool IsPlayer(this ICommandSender sender) => sender is Player p && !string.IsNullOrEmpty(p.UserId);
+ internal static bool IsPlayer(this ICommandSender sender) => sender is Player p && !string.IsNullOrEmpty(p.UserID);
- internal static bool IsPermitted(this ICommandSender sender, string[] commandKey) => sender.IsPermitted(commandKey, false, out string[] reply);
+ internal static bool IsPermitted(this ICommandSender sender, string[] commandKey) => sender.IsPermitted(commandKey, false, out _);
- internal static bool IsPermitted(this ICommandSender sender, string[] commandKey, bool mustBeListed) => sender.IsPermitted(commandKey, mustBeListed, out string[] reply);
+ internal static bool IsPermitted(this ICommandSender sender, string[] commandKey, bool mustBeListed) => sender.IsPermitted(commandKey, mustBeListed, out _);
internal static bool IsPermitted(this ICommandSender sender, string[] commandKey, out string[] denied) => sender.IsPermitted(commandKey, false, out denied);
internal static bool IsPermitted(this ICommandSender sender, string[] commandKey, bool mustBeListed, out string[] denied)
{
- denied = new string[] { "Error during command whitelist calculation!" };
- if (sender is Player pl)
+ denied = new string[0];
+ try
{
- if (commandKey.Length < 1)
- return true;
- string[] masterWhitelist = ConfigManager.Manager.Config.GetListValue("admintoolbox_master_whitelist", new string[] { });
- if (masterWhitelist.ContainsPlayer(pl))
- return true;
-
- int validConfigs = 0;
- foreach (string command in commandKey)
+ if (sender is Player pl)
{
- command.Trim();
- if (string.IsNullOrEmpty(command)) continue;
- //Gets a array of whitelisted users (if any)
- string[] configList = ConfigManager.Manager.Config.GetListValue("admintoolbox_" + command.ToLower() + "_whitelist", new string[0]);
- if (configList.Length > 0)
- validConfigs++;
- if (configList.ContainsPlayer(pl))
+ if (commandKey.Length < 1)
return true;
+ string[] masterWhitelist = ConfigManager.Manager.Config.GetListValue("admintoolbox_master_whitelist", new string[] { });
+ if (masterWhitelist.ContainsPlayer(pl))
+ return true;
+
+ int validConfigs = 0;
+ foreach (string command in commandKey)
+ {
+ command.Trim();
+ if (string.IsNullOrEmpty(command)) continue;
+ //Gets a array of whitelisted users (if any)
+ string[] configList = ConfigManager.Manager.Config.GetListValue("admintoolbox_" + command.ToLower() + "_whitelist", new string[0]);
+ if (configList.Length > 0)
+ validConfigs++;
+ if (configList.ContainsPlayer(pl))
+ return true;
+ }
+ string reply = "You are not permitted to use the (" + string.Join(" / ", commandKey) + ") command!";
+ denied = mustBeListed ? new string[] { reply, "You are required to be spesificly whitelisted to use this command." } : new string[] { reply };
+ return (mustBeListed || ConfigManager.Manager.Config.GetBoolValue("admintoolbox_whitelist_required", false)) && validConfigs < 1
+ ? false
+ : !(validConfigs > 0);
}
- string reply = "You are not permitted to use the (" + string.Join(" / ", commandKey) + ") command!";
- denied = mustBeListed ? new string[] { reply, "You are required to be spesificly whitelisted to use this command." } : new string[] { reply };
- return (mustBeListed || ConfigManager.Manager.Config.GetBoolValue("admintoolbox_whitelist_required", false)) && validConfigs < 1
- ? false
- : !(validConfigs > 0);
+ else
+ return true;
+ }
+ catch
+ {
+ denied = new string[] { "Error during command whitelist calculation!" };
+ return false;
}
- else
- return true;
}
internal static bool ContainsPlayer(this Dictionary dict, Player player)
- => AdminToolbox.ATPlayerDict?.ContainsKey(player?.UserId) ?? false;
+ => dict?.ContainsKey(player?.UserID) ?? false;
- internal static void ResetPlayerBools(this Dictionary.KeyCollection dict)
+ internal static void ResetPlayerBools(this Dictionary dict)
{
- string[] keys = dict.ToArray();
+ string[] keys = dict.Keys.ToArray();
if (keys.Length > 0)
{
foreach (string key in keys)
{
if (AdminToolbox.ATPlayerDict.ContainsKey(key) && !AdminToolbox.ATPlayerDict[key].keepSettings)
{
- SetPlayerVariables.SetPlayerBools(key, godMode: false, dmgOff: false, destroyDoor: false, lockDown: false, instantKill: false);
+ foreach (FieldInfo field in typeof(PlayerSettings).GetFields().Where(p => p.FieldType == typeof(bool)))
+ field.SetValue(AdminToolbox.ATPlayerDict[key], false);
+ //SetPlayerVariables.SetPlayerBools(key, godMode: false, dmgOff: false, destroyDoor: false, lockDown: false, instantKill: false);
}
}
}
@@ -163,15 +170,15 @@ internal static bool TryGetVector(this Dictionary dict, strin
///
internal static void Cleanup(this Dictionary dict)
{
- string[] currentPlayers = PluginManager.Manager.Server.GetPlayers().UserIdsToArray();
+ string[] currentPlayers = PluginManager.Manager.Server.GetPlayers().UserIDsToArray();
Dictionary newDict = new Dictionary(dict);
if (newDict.Count > 0)
{
foreach (KeyValuePair kp in newDict)
{
- if (!currentPlayers.Any(s => s == kp.Key) && !kp.Value.keepSettings && Math.Abs((DateTime.Now - kp.Value.JoinTime).TotalMinutes - Server.Round.Duration) > 2)
+ if (!currentPlayers.Any(s => s == kp.Key) && !kp.Value.keepSettings && Math.Abs((DateTime.UtcNow - kp.Value.JoinTime).TotalMinutes - Server.Round.Duration) > 2)
{
- AdminToolbox.atfileManager.PlayerStatsFileManager(kp.Key, Managers.ATFileManager.PlayerFile.Write);
+ AdminToolbox.FileManager.PlayerStatsFileManager(kp.Key, Managers.ATFile.PlayerFile.Write);
dict.Remove(kp.Key);
}
}
@@ -183,23 +190,24 @@ internal static void Cleanup(this Dictionary dict)
///
public static string ToColoredMultiAdminTeam(this Player player)
{
- if (!AdminToolbox.isColored) return player.TeamRole.Name;
- switch ((Team)player.TeamRole.Team)
+ if (!AdminToolbox.isColored)
+ return player.PlayerRole.Name;
+ switch ((Team)player.PlayerRole.Team)
{
case Team.SCP:
- return "@#fg=Red;" + player.TeamRole.Name + "@#fg=Default;";
+ return "@#fg=Red;" + player.PlayerRole.Name + "@#fg=Default;";
case Team.MTF:
- return "@#fg=Blue;" + player.TeamRole.Name + "@#fg=Default;";
+ return "@#fg=Blue;" + player.PlayerRole.Name + "@#fg=Default;";
case Team.CHI:
- return "@#fg=Green;" + player.TeamRole.Name + "@#fg=Default;";
+ return "@#fg=Green;" + player.PlayerRole.Name + "@#fg=Default;";
case Team.RSC:
- return "@#fg=Yellow;" + player.TeamRole.Name + "@#fg=Default;";
+ return "@#fg=Yellow;" + player.PlayerRole.Name + "@#fg=Default;";
case Team.CDP:
- return "@#fg=Orange;" + player.TeamRole.Name + "@#fg=Default;";
+ return "@#fg=Orange;" + player.PlayerRole.Name + "@#fg=Default;";
case Team.TUT:
- return "@#fg=Green;" + player.TeamRole.Name + "@#fg=Default;";
+ return "@#fg=Green;" + player.PlayerRole.Name + "@#fg=Default;";
default:
- return player.TeamRole.Name;
+ return player.PlayerRole.Name;
}
}
@@ -208,22 +216,22 @@ public static string ToColoredMultiAdminTeam(this Player player)
///
public static string ToColoredRichTextRole(this Player player)
{
- switch ((Team)player.TeamRole.Team)
+ switch ((Team)player.PlayerRole.Team)
{
case Team.SCP:
- return "" + player.TeamRole.Name + "";
+ return "" + player.PlayerRole.Name + "";
case Team.MTF:
- return "" + player.TeamRole.Name + "";
+ return "" + player.PlayerRole.Name + "";
case Team.CHI:
- return "" + player.TeamRole.Name + "";
+ return "" + player.PlayerRole.Name + "";
case Team.RSC:
- return "" + player.TeamRole.Name + "";
+ return "" + player.PlayerRole.Name + "";
case Team.CDP:
- return "" + player.TeamRole.Name + "";
+ return "" + player.PlayerRole.Name + "";
case Team.TUT:
- return "" + player.TeamRole.Name + "";
+ return "" + player.PlayerRole.Name + "";
default:
- return player.TeamRole.Name;
+ return player.PlayerRole.Name;
}
}
}
diff --git a/AdminToolbox/AdminToolbox/API/GetFromString.cs b/AdminToolbox/AdminToolbox/API/GetFromString.cs
new file mode 100644
index 0000000..cd52d2d
--- /dev/null
+++ b/AdminToolbox/AdminToolbox/API/GetFromString.cs
@@ -0,0 +1,111 @@
+using System.Linq;
+using System.Collections.Generic;
+using Smod2;
+using Smod2.API;
+
+namespace AdminToolbox.API
+{
+ ///
+ /// Class containing the constructor
+ ///
+ public static class GetFromString
+ {
+ private static Server Server => PluginManager.Manager.Server;
+
+ ///
+ /// Returns from
+ ///
+ ///
+ public static Player GetPlayer(string arg)
+ {
+ Player playerOut = null;
+ if (string.IsNullOrEmpty(arg))
+ return null;
+ try
+ {
+ if (byte.TryParse(arg, out byte pID))
+ {
+ foreach (Player pl in Server.GetPlayers())
+ if (pl.PlayerID == pID)
+ {
+ playerOut = pl;
+ break;
+ }
+ }
+ else if (long.TryParse(arg, out long ID))
+ {
+ foreach (Player pl in Server.GetPlayers())
+ if (pl.UserID.Contains(ID.ToString()))
+ {
+ playerOut = pl;
+ break;
+ }
+ }
+ else
+ {
+ playerOut = Server.GetPlayers(arg.ToLower()).OrderBy(s => s.Name.Length).FirstOrDefault();
+ }
+ }
+ catch (System.Exception e)
+ {
+ AdminToolbox.singleton.Debug($"[GetPlayer Exception]: " + e);
+ }
+ return playerOut;
+ }
+
+ ///
+ /// Gets list of players from param
+ ///
+ /// of
+ public static Player[] GetGroup(string name)
+ {
+ if (!name.StartsWith("#"))
+ name = name.TrimStart(new char[] { '#' }).ToLower();
+ if (!string.IsNullOrEmpty(name))
+ {
+ return Server.GetPlayers().Where(n => n.GetUserGroup().Name.ToLower().Contains(name) || n.GetRankName().ToLower().Contains(name) || n.GetUserGroup().BadgeText.ToLower().Contains(name)).ToArray();
+ }
+ return null;
+ }
+
+ ///
+ /// Gets list of players from param
+ ///
+ /// of
+ public static Player[] GetRole(string name)
+ {
+ if (!name.StartsWith("$"))
+ name = name.TrimStart(new char[] { '$' }).ToLower();
+ if (!string.IsNullOrEmpty(name))
+ {
+ return Server.GetPlayers().Where(n => n.PlayerRole.RoleID.ToString().ToLower().Contains(name)).ToArray();
+ }
+ return null;
+ }
+
+ ///
+ /// Gets list of players from param
+ ///
+ /// of
+ public static Player[] GetTeam(string name)
+ {
+ if (!name.StartsWith("$"))
+ name = name.TrimStart(new char[] { '$' }).ToLower();
+ if (!string.IsNullOrEmpty(name))
+ {
+ return Server.GetPlayers().Where(n => n.PlayerRole.Team.ToString().ToLower().Contains(name)).ToArray();
+ }
+ return null;
+ }
+
+ ///
+ /// Attempts to get player from .
+ ///
+ /// based on success
+ public static bool TryGetPlayer(string arg, out Player player)
+ {
+ player = GetPlayer(arg);
+ return player != null;
+ }
+ }
+}
diff --git a/AdminToolbox/AdminToolbox/API/GetPlayerFromString.cs b/AdminToolbox/AdminToolbox/API/GetPlayerFromString.cs
deleted file mode 100644
index c9e5b0d..0000000
--- a/AdminToolbox/AdminToolbox/API/GetPlayerFromString.cs
+++ /dev/null
@@ -1,69 +0,0 @@
-using System.Linq;
-using Smod2;
-using Smod2.API;
-
-namespace AdminToolbox.API
-{
- ///
- /// Class containing the constructor
- ///
- public class GetPlayerFromString
- {
- private static Server Server => PluginManager.Manager.Server;
-
- ///
- /// Returns from
- ///
- public static Player GetPlayer(string args)
- {
- Player playerOut = null;
- if (short.TryParse(args, out short pID))
- {
- foreach (Player pl in Server.GetPlayers())
- if (pl.PlayerId == pID)
- return pl;
- }
- else if (long.TryParse(args, out long sID))
- {
- foreach (Player pl in Server.GetPlayers())
- if (pl.UserId == sID.ToString())
- return pl;
- }
- else
- {
- return Server.GetPlayers(args.ToLower()).OrderBy(s => s.Name.Length).FirstOrDefault();
- /*
- //Takes a string and finds the closest player from the playerlist
- int maxNameLength = 31, LastnameDifference = 31;
- string str1 = args.ToLower();
- foreach (Player pl in Server.GetPlayers(str1))
- {
- if (!pl.Name.ToLower().Contains(args.ToLower()))
- continue;
- if (str1.Length < maxNameLength)
- {
- int x = maxNameLength - str1.Length;
- int y = maxNameLength - pl.Name.Length;
- string str2 = pl.Name;
- for (int i = 0; i < x; i++)
- {
- str1 += "z";
- }
- for (int i = 0; i < y; i++)
- {
- str2 += "z";
- }
- int nameDifference = LevenshteinDistance.Compute(str1, str2);
- if (nameDifference < LastnameDifference)
- {
- LastnameDifference = nameDifference;
- playerOut = pl;
- }
- }
- }
- */
- }
- return playerOut;
- }
- }
-}
diff --git a/AdminToolbox/AdminToolbox/API/JailHandler.cs b/AdminToolbox/AdminToolbox/API/JailHandler.cs
index a739488..5dce5cc 100644
--- a/AdminToolbox/AdminToolbox/API/JailHandler.cs
+++ b/AdminToolbox/AdminToolbox/API/JailHandler.cs
@@ -14,11 +14,21 @@ public class JailHandler
///
/// jail position
///
- public static Vector JailPos => AdminToolbox.WarpVectorDict?["jail"]?.Vector.ToSMVector() ?? new Vector(53, 1020, -44);
+ public static Vector JailPos
+ {
+ get
+ {
+ if (AdminToolbox.WarpVectorDict.TryGetValue("jail", out WarpPoint wp))
+ return wp.Vector.ToSMVector();
+ else
+ return new Vector(53, 1020, -44);
+ }
+ }
private static Server Server => PluginManager.Manager.Server;
private static void Debug(string message) => AdminToolbox.singleton.Debug("[JailHandler]: " + message);
+ private static void Info(string message) => AdminToolbox.singleton.Info("[JailHandler]: " + message);
///
/// Checks the players marked as "Jailed" to see if they are at where they're supposed to be
@@ -29,9 +39,10 @@ internal static void CheckJailedPlayers()
Player[] jailedPlayers = Server.GetPlayers().ToArray().JailedPlayers();
if (jailedPlayers.Length > 0)
foreach (Player pl in jailedPlayers)
- if (AdminToolbox.ATPlayerDict.ContainsKey(pl.UserId))
+ if (AdminToolbox.ATPlayerDict.ContainsKey(pl.UserID))
if (!pl.IsInsideJail()) SendToJail(pl);
- else if (AdminToolbox.ATPlayerDict[pl.UserId].JailedToTime <= DateTime.Now) ReturnFromJail(pl);
+ else if (AdminToolbox.ATPlayerDict[pl.UserID].JailedToTime <= DateTime.UtcNow)
+ ReturnFromJail(pl);
}
///
@@ -45,30 +56,30 @@ internal static void CheckJailedPlayers()
/// the time to jail the player. Null sets the time to remaining time, or if thats null, one year
public static bool SendToJail(Smod2.API.Player player, DateTime? jailedToTime)
{
- if (player == null || player.TeamRole.Role == Smod2.API.RoleType.SPECTATOR || player.OverwatchMode) return false;
+ if (player == null || player.PlayerRole.RoleID == Smod2.API.RoleType.SPECTATOR || player.OverwatchMode) return false;
Debug($"Attempting to jail {player.Name}");
- if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserId, out PlayerSettings psetting))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserID, out PlayerSettings psetting))
{
- if (!jailedToTime.HasValue || jailedToTime < DateTime.Now)
+ if (!jailedToTime.HasValue || jailedToTime < DateTime.UtcNow)
Debug($"Jail time for \"{player.Name}\" not specified, jailing for a year.");
- psetting.JailedToTime = jailedToTime ?? ((psetting.JailedToTime > DateTime.Now) ? psetting.JailedToTime : DateTime.Now.AddYears(1));
+ psetting.JailedToTime = jailedToTime ?? ((psetting.JailedToTime > DateTime.UtcNow) ? psetting.JailedToTime : DateTime.UtcNow.AddYears(1));
//Saves original variables
psetting.originalPos = player.GetPosition();
if (!psetting.isJailed)
{
- psetting.previousRole = player.TeamRole.Role;
+ psetting.previousRole = player.PlayerRole.RoleID;
psetting.playerPrevInv = player.GetInventory();
- psetting.previousHealth = player.GetHealth();
- psetting.prevAmmo5 = player.GetAmmo(AmmoType.DROPPED_5);
- psetting.prevAmmo7 = player.GetAmmo(AmmoType.DROPPED_7);
- psetting.prevAmmo9 = player.GetAmmo(AmmoType.DROPPED_9);
+ psetting.previousHealth = player.Health;
+
+ foreach (AmmoType a in typeof(AmmoType).GetEnumValues())
+ if (a != AmmoType.NONE)
+ psetting.Ammo[a] = player.GetAmmo(a);
}
//Changes role to Tutorial, teleports to jail, removes inv.
Debug($"Variables stored, sending \"{player.Name}\" to jail");
player.ChangeRole(Smod2.API.RoleType.TUTORIAL, true, false);
player.Teleport(JailPos, true);
- foreach (SMItem item in player.GetInventory())
- item.Remove();
+ player.ClearInventory();
psetting.isJailed = true;
return true;
}
@@ -86,35 +97,34 @@ public static bool SendToJail(Smod2.API.Player player, DateTime? jailedToTime)
/// the player to return
public static bool ReturnFromJail(Player player)
{
- if (player == null || string.IsNullOrEmpty(player.UserId.Trim()))
+ if (player == null || string.IsNullOrEmpty(player.UserID.Trim()))
{
- Debug("Return: Player or UserId null/empty");
+ Debug("Return: Player or UserID null/empty");
return false;
}
Debug($"Attempting to unjail \"{player.Name}\"");
- if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserId, out PlayerSettings psetting))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserID, out PlayerSettings psetting))
{
psetting.isJailed = false;
- psetting.JailedToTime = DateTime.Now;
+ psetting.JailedToTime = DateTime.UtcNow;
player.ChangeRole(psetting.previousRole, true, false);
player.Teleport(psetting.originalPos, true);
- player.SetHealth(psetting.previousHealth);
+ player.Health = psetting.previousHealth;
if (psetting.playerPrevInv != null)
{
- foreach (SMItem item in player.GetInventory())
- item.Remove();
+ player.ClearInventory();
foreach (SMItem item in psetting.playerPrevInv)
player.GiveItem(item.ItemType);
}
- player.SetAmmo(AmmoType.DROPPED_5, psetting.prevAmmo5);
- player.SetAmmo(AmmoType.DROPPED_7, psetting.prevAmmo7);
- player.SetAmmo(AmmoType.DROPPED_9, psetting.prevAmmo9);
- AdminToolbox.ATPlayerDict[player.UserId].playerPrevInv = null;
+ foreach (AmmoType a in typeof(AmmoType).GetEnumValues())
+ if (a != AmmoType.NONE)
+ player.SetAmmo(a, psetting.Ammo[a]);
+ AdminToolbox.ATPlayerDict[player.UserID].playerPrevInv = null;
return true;
}
else
{
- AdminToolbox.singleton.Info("Could not return player from jail! Player not in PlayerDict!");
+ Info("Could not return player from jail! Player not in PlayerDict!");
return false;
}
}
diff --git a/AdminToolbox/AdminToolbox/API/PlayerSettings.cs b/AdminToolbox/AdminToolbox/API/PlayerSettings.cs
index 5ce39c6..99d895f 100644
--- a/AdminToolbox/AdminToolbox/API/PlayerSettings.cs
+++ b/AdminToolbox/AdminToolbox/API/PlayerSettings.cs
@@ -1,14 +1,23 @@
using System;
using System.Collections.Generic;
using Smod2.API;
-using SMItem = Smod2.API.Item;
namespace AdminToolbox.API
{
public class PlayerInfo
{
+ ///
+ /// Last known nickname of the player
+ ///
public string LastNickname { get; internal set; } = "Unknown";
- public string UserId { get; internal set; } = "00000000000000000";
+ ///
+ /// The player's UserID
+ ///
+ public string UserID { get; internal set; } = "00000000000000000";
+
+ ///
+ /// The last known instance of the player's DNT setting
+ ///
public bool DNT { get; internal set; } = false;
public string FirstJoin { get; set; } = "";
@@ -30,8 +39,6 @@ public class PlayerStats
public int EscapeCount { get; set; } = 0;
public double MinutesPlayed { get; set; } = 0.1;
-
- public PlayerStats() { }
}
///
/// is 's settings
@@ -56,21 +63,20 @@ public bool
internal float
previousHealth = 100;
- internal int
- prevAmmo5 = 0,
- prevAmmo7 = 0,
- prevAmmo9 = 0;
+ internal Dictionary Ammo =
+ new Dictionary() { [AmmoType.AMMO_44_CAL] = 0, [AmmoType.AMMO_12_GAUGE] = 0,
+ [AmmoType.AMMO_556_X45] = 0, [AmmoType.AMMO_762_X39] = 0, [AmmoType.AMMO_9_X19] = 0};
public Vector DeathPos = Vector.Zero;
internal Vector originalPos = Vector.Zero;
- internal Smod2.API.RoleType previousRole = Smod2.API.RoleType.CLASSD;
- internal List playerPrevInv = new List();
+ internal Smod2.API.RoleType previousRole = Smod2.API.RoleType.D_CLASS;
+ internal List playerPrevInv = new List();
- internal Smod2.API.ItemType InfiniteItem = Smod2.API.ItemType.NULL;
+ internal Smod2.API.ItemType InfiniteItem = Smod2.API.ItemType.NONE;
- public DateTime JailedToTime { get; internal set; } = DateTime.Now;
- public DateTime JoinTime { get; internal set; } = DateTime.Now;
+ public DateTime JailedToTime { get; internal set; } = DateTime.UtcNow;
+ public DateTime JoinTime { get; internal set; } = DateTime.UtcNow;
- public PlayerSettings(string UserId) => this.PlayerInfo.UserId = UserId;
+ public PlayerSettings(string UserID) => this.PlayerInfo.UserID = UserID;
}
}
diff --git a/AdminToolbox/AdminToolbox/API/SetPlayerVariables.cs b/AdminToolbox/AdminToolbox/API/SetPlayerVariables.cs
index c2aa84d..49c8079 100644
--- a/AdminToolbox/AdminToolbox/API/SetPlayerVariables.cs
+++ b/AdminToolbox/AdminToolbox/API/SetPlayerVariables.cs
@@ -9,12 +9,12 @@ namespace AdminToolbox.API
public static class SetPlayerVariables
{
///
- /// For setting bools by
- /// Returns false if is not in
+ /// For setting bools by
+ /// Returns false if is not in
///
- public static bool SetPlayerBools(string UserId, bool? spectatorOnly = null, bool? godMode = null, bool? dmgOff = null, bool? destroyDoor = null, bool? keepSettings = null, bool? lockDown = null, bool? instantKill = null, bool? isJailed = null)
+ public static bool SetPlayerBools(string UserID, bool? spectatorOnly = null, bool? godMode = null, bool? dmgOff = null, bool? destroyDoor = null, bool? keepSettings = null, bool? lockDown = null, bool? instantKill = null, bool? isJailed = null)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(UserId, out PlayerSettings setting))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(UserID, out PlayerSettings setting))
{
setting.overwatchMode = spectatorOnly ?? setting.overwatchMode;
setting.godMode = godMode ?? setting.godMode;
@@ -31,29 +31,29 @@ public static bool SetPlayerBools(string UserId, bool? spectatorOnly = null, boo
}
///
/// For setting bools on a
- /// Returns false if 's UserId is not in
+ /// Returns false if 's UserID is not in
///
public static bool SetPlayerBools(Player player, bool? spectatorOnly = null, bool? godMode = null, bool? dmgOff = null, bool? destroyDoor = null, bool? keepSettings = null, bool? lockDown = null, bool? instantKill = null, bool? isJailed = null)
- => SetPlayerBools(player.UserId, spectatorOnly, godMode, dmgOff, destroyDoor, keepSettings, lockDown, instantKill, isJailed);
+ => SetPlayerBools(player.UserID, spectatorOnly, godMode, dmgOff, destroyDoor, keepSettings, lockDown, instantKill, isJailed);
///
/// For setting bools on a list of s
- /// Returns false if one or more of UserId's is not in
+ /// Returns false if one or more of UserID's is not in
///
public static bool SetPlayerBools(List players, bool? spectatorOnly = null, bool? godMode = null, bool? dmgOff = null, bool? destroyDoor = null, bool? keepSettings = null, bool? lockDown = null, bool? instantKill = null, bool? isJailed = null)
{
int failiures = 0;
foreach (Player player in players)
- if (!SetPlayerBools(player.UserId, spectatorOnly, godMode, dmgOff, destroyDoor, keepSettings, lockDown, instantKill, isJailed))
+ if (!SetPlayerBools(player.UserID, spectatorOnly, godMode, dmgOff, destroyDoor, keepSettings, lockDown, instantKill, isJailed))
failiures++;
return !(failiures > 0);
}
///
/// For setting
- /// Returns false if is not in
+ /// Returns false if is not in
///
- public static bool SetPlayerStats(string UserId, int? Kills = null, int? TeamKills = null, int? Deaths = null, int? RoundsPlayed = null, int? BanCount = null)
+ public static bool SetPlayerStats(string UserID, int? Kills = null, int? TeamKills = null, int? Deaths = null, int? RoundsPlayed = null, int? BanCount = null)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(UserId, out PlayerSettings settings))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(UserID, out PlayerSettings settings))
{
PlayerStats stats = settings.PlayerStats;
stats.Kills = Kills ?? stats.Kills;
diff --git a/AdminToolbox/AdminToolbox/API/Utility.cs b/AdminToolbox/AdminToolbox/API/Utility.cs
index 35f2cf2..ad6e3ee 100644
--- a/AdminToolbox/AdminToolbox/API/Utility.cs
+++ b/AdminToolbox/AdminToolbox/API/Utility.cs
@@ -1,55 +1,56 @@
using System;
-using System.Linq;
+using Smod2;
using Smod2.API;
+using System.Collections.Generic;
+using System.Globalization;
+using SMRoleType = Smod2.API.RoleType;
+using SMItemType = Smod2.API.ItemType;
namespace AdminToolbox.API
{
+ using API.Extentions;
+ using Webhook;
public static class Utility
{
+ private static IConfigFile Config => ConfigManager.Manager.Config;
+
///
- /// Safely getting a from an .
+ /// Safely getting a from an .
/// Returns based on success
- /// Invalid parameters returns
+ /// Invalid parameters returns
///
- public static bool TryParseRole(int roleID, out Smod2.API.RoleType role)
+ public static bool TryParseRole(int roleID, out SMRoleType role)
{
- role = Smod2.API.RoleType.UNASSIGNED;
try
{
- int[] validRoles = Enum.GetValues(typeof(Smod2.API.RoleType)).Cast().ToArray();
- if (!validRoles.Contains(roleID))
- return false;
- else
- {
- role = (Smod2.API.RoleType)roleID;
- return true;
- }
+ role = (SMRoleType)roleID;
}
- catch (Exception e)
+ catch
{
- AdminToolbox.singleton.Info("AT " + AdminToolbox.AT_Version + "-" + AdminToolbox.AT_Revision +
- "\nSMOD " + Smod2.PluginManager.GetSmodVersion() + "-" + Smod2.PluginManager.GetSmodBuild() + "\n" + e);
+ role = SMRoleType.NONE;
return false;
}
+ return true;
}
///
/// Safely getting a from an .
/// Returns based on success
- /// Invalid parameters returns
+ /// Invalid parameters returns
///
- public static bool TryParseItem(int itemID, out Smod2.API.ItemType itemType)
+ public static bool TryParseItem(int itemID, out SMItemType itemType)
{
- itemType = Smod2.API.ItemType.NULL;
- int[] validItems = Enum.GetValues(typeof(Smod2.API.ItemType)).Cast().ToArray();
- if (!validItems.Contains(itemID))
- return false;
- else
+ try
{
- itemType = (Smod2.API.ItemType)itemID;
- return true;
+ itemType = (SMItemType)itemID;
+ }
+ catch
+ {
+ itemType = SMItemType.NONE;
+ return false;
}
+ return true;
}
///
@@ -57,22 +58,30 @@ public static bool TryParseItem(int itemID, out Smod2.API.ItemType itemType)
/// Returns based on success
/// Tries to cast to first, then compares names
///
- public static bool TryParseItem(string item, out Smod2.API.ItemType itemType)
+ public static bool TryParseItem(string item, out SMItemType itemType)
{
- if (int.TryParse(item, out int x))
- return TryParseItem(x, out itemType);
-
- itemType = Smod2.API.ItemType.NULL;
+ itemType = SMItemType.NONE;
- foreach (Smod2.API.ItemType i in Enum.GetValues(typeof(Smod2.API.ItemType)))
+ try
{
- if (i.ToString().ToUpper().Contains(item.ToUpper()))
+ if (int.TryParse(item, out int x))
+ return TryParseItem(x, out itemType);
+
+ foreach (SMItemType i in Enum.GetValues(typeof(SMItemType)))
{
- itemType = i;
- return true;
+ if (i.ToString().ToUpper().Contains(item.ToUpper()))
+ {
+ itemType = i;
+ return true;
+ }
}
+ return true;
+ }
+ catch
+ {
+ itemType = SMItemType.NONE;
+ return false;
}
- return true;
}
///
@@ -84,31 +93,49 @@ public static bool TryParseItem(string item, out Smod2.API.ItemType itemType)
public static readonly int[]
HumanDamageTypes = {
(int)DamageType.COM15,
- (int)DamageType.E11_STANDARD_RIFLE,
- (int)DamageType.P90,
- (int)DamageType.MP7,
+ (int)DamageType.AK,
+ (int)DamageType.COM18,
+ (int)DamageType.CROSSVEC,
+ (int)DamageType.E11_SR,
+ (int)DamageType.FSP9,
(int)DamageType.LOGICER,
- (int)DamageType.FRAG
+ (int)DamageType.EXPLOSION,
+ (int)DamageType.MICRO_HID,
+ (int)DamageType.REVOLVER,
+ (int)DamageType.UNKNOWN_FIREARM,
+ (int)DamageType.SHOTGUN
},
ScpDamagesTypes = {
(int)DamageType.SCP_049,
(int)DamageType.SCP_049_2,
(int)DamageType.SCP_096,
- (int)DamageType.SCP_106,
+ //(int)DamageType.SCP_106,
(int)DamageType.SCP_173,
(int)DamageType.SCP_939
},
NineTailsTeam = {
- (int)Team.MTF,
- (int)Team.RSC
+ (int)TeamType.MTF,
+ (int)TeamType.SCIENTIST
},
ChaosTeam = {
- (int)Team.CHI,
- (int)Team.CDP
+ (int)TeamType.CHAOS_INSURGENCY,
+ (int)TeamType.D_CLASS
};
- public static readonly DamageType Human = DamageType.COM15 | DamageType.E11_STANDARD_RIFLE | DamageType.P90 | DamageType.MP7 | DamageType.LOGICER | DamageType.FRAG;
- public static readonly DamageType SCP = DamageType.SCP_049 | DamageType.SCP_049_2 | DamageType.SCP_096 | DamageType.SCP_106 | DamageType.SCP_173 | DamageType.SCP_939;
+ public static readonly DamageType Human = DamageType.COM15 |
+ DamageType.COM15 |
+ DamageType.AK |
+ DamageType.COM18 |
+ DamageType.CROSSVEC |
+ DamageType.E11_SR |
+ DamageType.FSP9 |
+ DamageType.LOGICER |
+ DamageType.EXPLOSION |
+ DamageType.MICRO_HID |
+ DamageType.REVOLVER |
+ DamageType.UNKNOWN_FIREARM |
+ DamageType.SHOTGUN;
+ public static readonly DamageType SCP = DamageType.SCP_049 | DamageType.SCP_049_2 | DamageType.SCP_096 |/* DamageType.SCP_106 |*/ DamageType.SCP_173 | DamageType.SCP_939;
///
@@ -117,15 +144,33 @@ public static readonly int[]
///
public static bool IsTeam(Player player1, Player player2)
{
- if (player1 == null || player2 == null || player1.PlayerId == player2.PlayerId)
+ if (player1 == null || player2 == null || player1.PlayerID == player2.PlayerID)
return false;
- if (NineTailsTeam.Contains((int)player1.TeamRole.Team) && NineTailsTeam.Contains((int)player2.TeamRole.Team))
+ if (NineTailsTeam.Contains((int)player1.PlayerRole.Team) && NineTailsTeam.Contains((int)player2.PlayerRole.Team))
return true;
- else if (ChaosTeam.Contains((int)player1.TeamRole.Team) && ChaosTeam.Contains((int)player2.TeamRole.Team))
+ else if (ChaosTeam.Contains((int)player1.PlayerRole.Team) && ChaosTeam.Contains((int)player2.PlayerRole.Team))
return true;
else
return false;
}
+
+ internal static DiscordWebhook BuildBanWebhook(Player player, int duration, string reason = "", string issuer = "")
+ {
+ DiscordWebhook webH;
+ List listOfFields = new List();
+ CultureInfo timeFormat = new CultureInfo("ja-JP");
+ listOfFields.AddField("Playername: ", player?.Name ?? "TEST", true);
+ listOfFields.AddField("Duration: ", (duration / 60).ToString("0", CultureInfo.InvariantCulture) + " minutes", true);
+ listOfFields.AddField("Timespan: ", $"[{DateTime.UtcNow.ToString(timeFormat)}] -> [{DateTime.UtcNow.AddSeconds(duration).ToString(timeFormat)}]");
+ if (!string.IsNullOrEmpty(reason))
+ listOfFields.AddField("Reason: ", reason, true);
+ if (Config.GetBoolValue("admintoolbox_ban_webhook_include_admin", false))
+ listOfFields.AddField("Issued By: ", string.IsNullOrEmpty(issuer) ? "Server" : issuer, true);
+
+ webH = new DiscordWebhook { embeds = new EmbedData[] { new EmbedData { author = new Author { name = "User Banned: " }, title = "", fields = listOfFields.ToArray() } } };
+
+ return webH;
+ }
}
}
diff --git a/AdminToolbox/AdminToolbox/API/WarpPoint.cs b/AdminToolbox/AdminToolbox/API/WarpPoint.cs
index 165977c..0163cb7 100644
--- a/AdminToolbox/AdminToolbox/API/WarpPoint.cs
+++ b/AdminToolbox/AdminToolbox/API/WarpPoint.cs
@@ -5,12 +5,11 @@ namespace AdminToolbox.API
///
/// The class uses for warp-points
///
- public class WarpPoint
+ public struct WarpPoint
{
public string Name { get; set; }
- public string Description { get; set; } = "";
+ public string Description { get; set; }
public ATVector Vector { get; set; }
- public WarpPoint() { }
}
///
diff --git a/AdminToolbox/AdminToolbox/AdminToolbox.cs b/AdminToolbox/AdminToolbox/AdminToolbox.cs
index e4f40b8..60d2bda 100644
--- a/AdminToolbox/AdminToolbox/AdminToolbox.cs
+++ b/AdminToolbox/AdminToolbox/AdminToolbox.cs
@@ -21,50 +21,36 @@ namespace AdminToolbox
name = "Admin Toolbox",
description = "Plugin for advanced admin tools",
id = "rnen.admin.toolbox",
- version = AT_Version + "-" + AT_Revision,
+ version = AT_Version + "-" + AT_Revision,
SmodMajor = 3,
- SmodMinor = 7,
+ SmodMinor = 10,
SmodRevision = 0
)]
public class AdminToolbox : Plugin
{
- internal const string AT_Version = "1.3.8";
- internal const string AT_Revision = "14";
-
- #region GitHub release info
- private DateTime LastOnlineCheck = DateTime.Now;
- private ATWeb.AT_LatestReleaseInfo LatestReleaseInfo;
+ internal const string AT_Version = "1.3.9";
+ internal const string AT_Revision = "0";
+ internal const string SModLetter = "";
internal static List waitForTeleports = new List();
- internal ATWeb.AT_LatestReleaseInfo GetGitReleaseInfo()
- {
- if (LastOnlineCheck.AddMinutes(5) < DateTime.Now || LatestReleaseInfo == null)
- {
- LatestReleaseInfo = ATWeb.GetOnlineInfo(this);
- LastOnlineCheck = DateTime.Now;
- }
- return LatestReleaseInfo;
- }
- #endregion
-
///
- /// The plugin's instance of
+ /// The plugin's instance of
///
- public static readonly LogManager logManager = new LogManager();
+ public static readonly LogManager LogManager = new LogManager();
///
- /// The plugin's instance instance of
+ /// The plugin's instance instance of
///
- public static readonly WarpManager warpManager = new WarpManager();
+ public static readonly WarpManager WarpManager = new WarpManager();
///
- /// The plugin's instance instance of
+ /// The plugin's instance instance of
///
- public static readonly ATFileManager atfileManager = new ATFileManager();
+ public static readonly ATFile FileManager = new ATFile();
internal static bool roundStatsRecorded = false;
- internal static readonly ATRoundStats roundStats = new ATRoundStats();
+ internal static readonly RoundStats RoundStats = new RoundStats();
internal static bool
isRoundFinished = false,
@@ -88,14 +74,14 @@ public static bool
#endif
///
- /// of containing the plugin's settings on all players. Uses as KEY
+ /// of containing the plugin's settings on all players. Uses as KEY
///
public static Dictionary ATPlayerDict { get; internal set; } = new Dictionary();
///
/// of all current warp vectors
///
- public static Dictionary WarpVectorDict = new Dictionary(warpManager.presetWarps);
+ public static Dictionary WarpVectorDict = new Dictionary(WarpManager.presetWarps);
///
/// round count
@@ -108,7 +94,11 @@ public static bool
/// Called when gets disabled
///
public override void OnDisable()
- => Debug(this.Details.name + " v." + this.Details.version + (isColored ? " - @#fg=Red;Disabled@#fg=Default;" : " - Disabled"));
+ {
+ UnRegisterCommands();
+ UnRegisterEvents();
+ Debug(this.Details.name + " v." + this.Details.version + (isColored ? " - @#fg=Red;Disabled@#fg=Default;" : " - Disabled"));
+ }
///
/// Called when gets enabled
@@ -116,7 +106,7 @@ public override void OnDisable()
public override void OnEnable()
{
singleton = this;
- ATFileManager.WriteVersionToFile();
+ ATFile.WriteVersionToFile();
Debug(this.Details.name + " v." + this.Details.version + (isColored ? " - @#fg=Green;Enabled@#fg=Default;" : " - Enabled"));
}
@@ -129,15 +119,14 @@ public override void Register()
this.RegisterCommands();
this.RegisterConfigs();
}
-
internal void RegisterEvents()
{
this.AddEventHandlers(new RoundEventHandler(this));
- this.AddEventHandler(typeof(IEventHandlerPlayerHurt), new DamageDetect(this));
- this.AddEventHandler(typeof(IEventHandlerPlayerDie), new DieDetect(this));
+ this.AddEventHandler(typeof(IEventHandlerPlayerHurt), new PlayerDamageEvent(this));
+ this.AddEventHandler(typeof(IEventHandlerPlayerDie), new PlayerDieEvent(this));
this.AddEventHandlers(new MyMiscEvents(this));
- this.AddEventHandler(typeof(IEventHandlerCheckRoundEnd), new LateOnCheckRoundEndEvent(this), Priority.Highest);
- this.AddEventHandler(typeof(IEventHandlerCheckEscape), new LateEscapeEventCheck(), Priority.Highest);
+ this.AddEventHandler(typeof(IEventHandlerCheckRoundEnd), new LateOnCheckRoundEndEvent(), Priority.LAST);
+ this.AddEventHandler(typeof(IEventHandlerCheckEscape), new LateEscapeEventCheck(), Priority.LAST);
}
internal void UnRegisterEvents() => EventManager.Manager.RemoveEventHandlers(this);
internal void RegisterCommands()
@@ -169,15 +158,15 @@ internal void RegisterCommands()
this.AddCommands(ATBanCommand.CommandAliases, new ATBanCommand(this));
this.AddCommands(KillCommand.CommandAliases, new KillCommand(this));
this.AddCommands(SpeakCommand.CommandAliases, new SpeakCommand());
- this.AddCommands(GhostCommand.CommandAliases, new GhostCommand(this));
+ this.AddCommands(GhostCommand.CommandAliases, new GhostCommand());
this.AddCommands(AT_HelpCommand.CommandAliases, new AT_HelpCommand());
this.AddCommands(ATCommand.CommandAliases, new ATCommand(this));
- this.AddCommands(ServerStatsCommand.CommandAliases, new ServerStatsCommand(this));
- this.AddCommands(LockDoorsCommand.CommandAliases, new LockDoorsCommand(this));
+ this.AddCommands(ServerStatsCommand.CommandAliases, new ServerStatsCommand());
+ this.AddCommands(LockDoorsCommand.CommandAliases, new LockDoorsCommand());
this.AddCommands(RespawnLockCommand.CommandAliases, new RespawnLockCommand());
- this.AddCommands(ClosestDoorCommand.CommandAliases, new ClosestDoorCommand(this));
- this.AddCommands(GrenadeModeCommand.CommandAliases, new GrenadeModeCommand(this));
- this.AddCommands(InfiniteItemCommand.CommandAliases, new InfiniteItemCommand(this));
+ this.AddCommands(ClosestDoorCommand.CommandAliases, new ClosestDoorCommand());
+ this.AddCommands(GrenadeModeCommand.CommandAliases, new GrenadeModeCommand());
+ this.AddCommands(InfiniteItemCommand.CommandAliases, new InfiniteItemCommand());
}
internal void UnRegisterCommands() => PluginManager.CommandManager.UnregisterCommands(this);
internal void RegisterConfigs()
@@ -191,10 +180,10 @@ internal void RegisterConfigs()
this.AddConfig(new ConfigSetting("admintoolbox_tutorial_dmg_allowed", new int[] { -1 }, true, "What (int)damagetypes TUTORIAL is allowed to take"));
#region Debug
- this.AddConfig(new ConfigSetting("admintoolbox_debug_damagetypes", new int[] { 5, 13, 14, 15, 16, 17 }, true, "What (int)damagetypes to debug"));
- this.AddConfig(new ConfigSetting("admintoolbox_debug_server", false, true, "Debugs damage dealt by server"));
- this.AddConfig(new ConfigSetting("admintoolbox_debug_spectator", false, true, "Debugs damage done to/by spectators"));
- this.AddConfig(new ConfigSetting("admintoolbox_debug_tutorial", false, true, "Debugs damage done to tutorial"));
+ this.AddConfig(new ConfigSetting("admintoolbox_debug_damagetypes", Utility.HumanDamageTypes, true, "What (int)damagetypes to debug"));
+ this.AddConfig(new ConfigSetting("admintoolbox_debug_server_damage", false, true, "Debugs damage dealt by server"));
+ this.AddConfig(new ConfigSetting("admintoolbox_debug_spectator_damage", false, true, "Debugs damage done to/by spectators"));
+ this.AddConfig(new ConfigSetting("admintoolbox_debug_tutorial_damage", false, true, "Debugs damage done to tutorial"));
this.AddConfig(new ConfigSetting("admintoolbox_debug_player_damage", false, true, "Debugs damage to all players except teammates"));
this.AddConfig(new ConfigSetting("admintoolbox_debug_friendly_damage", false, true, "Debugs damage to teammates"));
this.AddConfig(new ConfigSetting("admintoolbox_debug_player_kill", false, true, "Debugs player kills except teamkills"));
@@ -211,7 +200,7 @@ internal void RegisterConfigs()
#endregion
#region Cards
this.AddConfig(new ConfigSetting("admintoolbox_custom_nuke_cards", false, true, "Enables the use of custom keycards for the activation of the nuke"));
- this.AddConfig(new ConfigSetting("admintoolbox_nuke_card_list", new int[] { 6, 9, 11 }, true, "List of all cards that can enable the nuke"));
+ this.AddConfig(new ConfigSetting("admintoolbox_nuke_card_list", new int[] { (int)ItemType.KeycardContainmentEngineer, (int)ItemType.KeycardFacilityManager, (int)ItemType.KeycardO5 }, true, "List of all cards that can enable the nuke"));
#endregion
#region Log-Stuff
this.AddConfig(new ConfigSetting("admintoolbox_log_teamkills", false, true, "Writing logfiles for teamkills"));
@@ -223,56 +212,13 @@ internal void RegisterConfigs()
#endregion
#region Intercom
//this.AddConfig(new Smod2.Config.ConfigSetting("admintoolbox_intercom_whitelist", new string[] { string.Empty }, Smod2.Config.SettingType.LIST, true, "What ServerRank can use the Intercom to your specified settings"));
- this.AddConfig(new ConfigSetting("admintoolbox_intercom_UserId_blacklist", new string[0], true, "Blacklist of UserId's that cannot use the intercom"));
+ this.AddConfig(new ConfigSetting("admintoolbox_intercom_UserID_blacklist", new string[0], true, "Blacklist of UserID's that cannot use the intercom"));
this.AddConfig(new ConfigSetting("admintoolbox_intercomlock", false, true, "If set to true, locks the command for all non-whitelist players"));
#endregion
this.AddConfig(new ConfigSetting("admintoolbox_block_role_damage", new string[0], true, "What roles cannot attack other roles"));
this.AddConfig(new ConfigSetting("admintoolbox_ban_webhooks", new string[0], true, "Links to channel webhooks for bans"));
- //this.AddConfig(new Smod2.Config.ConfigSetting("admintoolbox_timedrestart_automessages", new string[] { "" }, Smod2.Config.SettingType.LIST, true, ""));
- //this.AddConfig(new Smod2.Config.ConfigSetting("atb_timedrestart_automessages", new string[] { "" }, Smod2.Config.SettingType.LIST, true, ""));
- }
-
-
- internal static void AddMissingPlayerVariables()
- {
- if (PluginManager.Manager.Server.GetPlayers().Count == 0) return;
- AddMissingPlayerVariables(PluginManager.Manager.Server.GetPlayers());
- }
- internal static void AddMissingPlayerVariables(Player player)
- => AddMissingPlayerVariables(new List() { player });
- internal static void AddMissingPlayerVariables(List players)
- => AddMissingPlayerVariables(players.ToArray());
- internal static void AddMissingPlayerVariables(Player[] players)
- {
- Player[] allPlayers = PluginManager.Manager.Server.GetPlayers().ToArray();
- if (allPlayers.Length == 0)
- {
- return;
- }
- else if (players == null || players.Length < 1)
- {
- players = allPlayers;
- }
- if (players.Length > 0)
- {
- foreach (Player player in players)
- {
- if (player != null && !string.IsNullOrEmpty(player.UserId))
- {
- AddToPlayerDict(player);
- }
- }
- }
- }
- private static void AddToPlayerDict(Player player)
- {
- if (player != null && player is Player p &&
- !string.IsNullOrEmpty(p.UserId) && !ATPlayerDict.ContainsKey(p.UserId))
- {
- ATPlayerDict.Add(p.UserId, new PlayerSettings(p.UserId));
- }
}
///
diff --git a/AdminToolbox/AdminToolbox/AdminToolbox.csproj b/AdminToolbox/AdminToolbox/AdminToolbox.csproj
index d30a76c..ad17949 100644
--- a/AdminToolbox/AdminToolbox/AdminToolbox.csproj
+++ b/AdminToolbox/AdminToolbox/AdminToolbox.csproj
@@ -9,7 +9,7 @@
Properties
AdminToolbox
AdminToolbox
- v4.7.1
+ v4.7.2
512
@@ -42,19 +42,12 @@
OnBuildSuccess
-
- False
- ..\Builds\Assembly-CSharp.dll
+
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\Assembly-CSharp.dll
False
-
- False
- ..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\Newtonsoft.Json.dll
- False
-
-
- False
- ..\Builds\Smod2.dll
+
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\Smod2.dll
False
@@ -64,23 +57,23 @@
- ..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.dll
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.dll
False
- ..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.CoreModule.dll
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.CoreModule.dll
False
- ..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.PhysicsModule.dll
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.PhysicsModule.dll
False
- ..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.UnityWebRequestModule.dll
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.UnityWebRequestModule.dll
False
- ..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.UnityWebRequestWWWModule.dll
+ ..\..\..\..\..\SCP_SL_SERVER\SCPSL_Data\Managed\UnityEngine.UnityWebRequestWWWModule.dll
False
@@ -88,7 +81,7 @@
-
+
@@ -130,7 +123,7 @@
-
+
diff --git a/AdminToolbox/AdminToolbox/Commands/AT_TemplateCommand.cs b/AdminToolbox/AdminToolbox/Commands/AT_TemplateCommand.cs
index 43e7639..c887c32 100644
--- a/AdminToolbox/AdminToolbox/Commands/AT_TemplateCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/AT_TemplateCommand.cs
@@ -34,7 +34,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
if (targetPlayer == null) { return new string[] { "Could not find player: " + args[0] }; ; }
//Adds player(s) to the AdminToolbox player dictionary
- AdminToolbox.AddMissingPlayerVariables(new List { targetPlayer, caller });
+ Managers.ATFile.AddMissingPlayerVariables(new List { targetPlayer, caller });
//Do whatever with the found player
return new string[] { "We did something to player: " + targetPlayer.Name + "!" };
diff --git a/AdminToolbox/AdminToolbox/Commands/Facility/ClosestDoorCommand.cs b/AdminToolbox/AdminToolbox/Commands/Facility/ClosestDoorCommand.cs
index cad0a64..3977b34 100644
--- a/AdminToolbox/AdminToolbox/Commands/Facility/ClosestDoorCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Facility/ClosestDoorCommand.cs
@@ -8,41 +8,29 @@ namespace AdminToolbox.Command
{
public class ClosestDoorCommand : ICommandHandler
{
- private readonly AdminToolbox plugin;
-
- private static IConfigFile Config => ConfigManager.Manager.Config;
-
private Server Server => PluginManager.Manager.Server;
- public ClosestDoorCommand(AdminToolbox plugin) => this.plugin = plugin;
-
public string GetCommandDescription() => "This is a description";
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ")";
public static readonly string[] CommandAliases = new string[] { "CLOSESTDOOR", "CLSDOOR", "ATDOOR", "ATD" };
public string[] OnCall(ICommandSender sender, string[] args)
{
- // Gets the caller as a "Player" object
-
if (args.Length > 0)
{
- //Get player from first arguement of OnCall
Player targetPlayer = args.Length > 1 ? Server.GetPlayers(args[0]).FirstOrDefault() : sender as Player;
- //If player could not be found, return reply to command user
if (targetPlayer == null)
return new string[] { "Could not find player" };
- //Adds player(s) to the AdminToolbox player dictionary
- AdminToolbox.AddMissingPlayerVariables(targetPlayer);
+ Managers.ATFile.AddMissingPlayerVariables(targetPlayer);
SMDoor closestDoor = null;
float dist = float.MaxValue;
- float newDist = float.MaxValue;
-
+
foreach (SMDoor d in Server.Map.GetDoors())
{
- newDist = Vector.Distance(d.Position, targetPlayer.GetPosition());
+ float newDist = Vector.Distance(d.Position, targetPlayer.GetPosition());
if (newDist < dist)
{
closestDoor = d;
@@ -50,35 +38,36 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
}
- string arg = args.Length > 1 ? args[1].ToUpper() : args[0].ToUpper();
-
- switch (arg)
+ switch ((args.Length > 1 ? args[1] : args[0]).ToUpper())
{
case "BREAK":
case "DESTROY":
case "DESTR":
case "BRK":
- closestDoor.Destroyed = true;
+ case "BR":
+ closestDoor.TriggerAction(DoorActions.DESTROYED);
return new string[] { "Closest door broken." };
case "LOCK":
case "L":
- closestDoor.Locked = true;
+ closestDoor.IsLocked = true;
return new string[] { "Closest door locked." };
case "UNLOCK":
case "UL":
case "!L":
- closestDoor.Locked = false;
+ closestDoor.IsLocked = false;
return new string[] { "Closest door unlocked." };
case "OPEN":
case "OP":
- closestDoor.Open = true;
+ case "O":
+ closestDoor.IsOpen = true;
return new string[] { "Closest door opened." };
case "CLOSE":
case "CL":
- closestDoor.Open = false;
+ case "C":
+ closestDoor.IsOpen = false;
return new string[] { "Closest door closed." };
default:
- return new string[] { "Word: " + arg + " is not recognized" };
+ return new string[] { "Arguements: \"" + string.Join(" ", args) + "\" is not recognized" };
}
}
else
diff --git a/AdminToolbox/AdminToolbox/Commands/Facility/JailCommand.cs b/AdminToolbox/AdminToolbox/Commands/Facility/JailCommand.cs
index 4cccd82..6671d53 100644
--- a/AdminToolbox/AdminToolbox/Commands/Facility/JailCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Facility/JailCommand.cs
@@ -19,16 +19,16 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (args.Length > 0)
{
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't get player: " + args[0] }; ; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
if (args.Length > 1)
{
if (int.TryParse(args[1], out int x))
{
if (x > 0)
{
- JailHandler.SendToJail(myPlayer, DateTime.Now.AddSeconds(x));
+ JailHandler.SendToJail(myPlayer, DateTime.UtcNow.AddSeconds(x));
return new string[] { "\"" + myPlayer.Name + "\" sent to jail for: " + x + " seconds." };
}
else
@@ -42,17 +42,19 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
else if (args.Length == 1)
{
- if (!AdminToolbox.ATPlayerDict.ContainsKey(myPlayer.UserId)) return new string[] { "Failed to jail/unjail " + myPlayer.Name + "!", "Error: Player not in dictionary" };
- if (AdminToolbox.ATPlayerDict[myPlayer.UserId].isJailed)
- {
- JailHandler.ReturnFromJail(myPlayer);
- return new string[] { "\"" + myPlayer.Name + "\" returned from jail" };
- }
- else
- {
- JailHandler.SendToJail(myPlayer);
- return new string[] { "\"" + myPlayer.Name + "\" sent to jail for 1 year" };
- }
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings playersetting))
+ if (playersetting.isJailed)
+ {
+ JailHandler.ReturnFromJail(myPlayer);
+ return new string[] { "\"" + myPlayer.Name + "\" returned from jail" };
+ }
+ else
+ {
+ JailHandler.SendToJail(myPlayer);
+ return new string[] { "\"" + myPlayer.Name + "\" sent to jail for 1 year" };
+ }
+ else
+ return new string[] { "Failed to jail/unjail " + myPlayer.Name + "!", "Error: Player not in dictionary" };
}
else
return new string[] { GetUsage() };
diff --git a/AdminToolbox/AdminToolbox/Commands/Facility/SpeakCommand.cs b/AdminToolbox/AdminToolbox/Commands/Facility/SpeakCommand.cs
index 95d75d8..065493e 100644
--- a/AdminToolbox/AdminToolbox/Commands/Facility/SpeakCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Facility/SpeakCommand.cs
@@ -11,7 +11,7 @@ public class SpeakCommand : ICommandHandler
private Server Server => PluginManager.Manager.Server;
public string GetCommandDescription() => "Sets specified player as intercom speaker";
- public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [PLAYERNAME/ID/UserId]";
+ public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [PLAYERNAME/ID/UserID]";
public static readonly string[] CommandAliases = new string[] { "ATSPEAK", "ATINTERCOM", "AT-SPEAK" };
@@ -25,7 +25,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
Server.Map.SetIntercomSpeaker(null);
return new string[] { "Stopped Broadcast" };
}
- Player myPlayer = (args.Length > 0) ? GetPlayerFromString.GetPlayer(args[0]) : null;
+ Player myPlayer = (args.Length > 0) ? GetFromString.GetPlayer(args[0]) : null;
if (myPlayer == null && sender is Player sendingPlayer)
myPlayer = sendingPlayer;
if (myPlayer == null)
diff --git a/AdminToolbox/AdminToolbox/Commands/Facility/WarpCommand.cs b/AdminToolbox/AdminToolbox/Commands/Facility/WarpCommand.cs
index 512dc70..2607f1e 100644
--- a/AdminToolbox/AdminToolbox/Commands/Facility/WarpCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Facility/WarpCommand.cs
@@ -32,9 +32,6 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
- if (sender != null && sender is Player p && p != null)
- AdminToolbox.AddMissingPlayerVariables(p);
-
if (args.Length > 0)
{
switch (args[0].ToUpper())
@@ -58,33 +55,35 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
return new string[] { str };
case "REFRESH":
- AdminToolbox.warpManager.RefreshWarps();
+ AdminToolbox.WarpManager.RefreshWarps();
return new string[] { "Refreshed warps!" };
case "REMOVE":
case "-":
- if (AdminToolbox.WarpVectorDict.ContainsKey(args[1].ToLower()))
- {
- AdminToolbox.WarpVectorDict.Remove(args[1].ToLower());
- AdminToolbox.warpManager.WriteWarpsToFile();
- return new string[] { "Warp point: " + args[1].ToLower() + " removed." };
- }
- else
- return new string[] { "Warp point " + args[1].ToLower() + " does not exist!" };
+ if (args.Length > 1)
+ if (AdminToolbox.WarpVectorDict.ContainsKey(args[1].ToLower()))
+ {
+ AdminToolbox.WarpVectorDict.Remove(args[1].ToLower());
+ AdminToolbox.WarpManager.WriteWarpsToFile();
+ return new string[] { "Warp point: " + args[1].ToLower() + " removed." };
+ }
+ else
+ return new string[] { "Warp point " + args[1].ToLower() + " does not exist!" };
+ return new string[] { GetUsage() };
case "ADD":
case "+":
if (args.Length > 2)
{
if (!AdminToolbox.WarpVectorDict.ContainsKey(args[2].ToLower()))
{
- Player myPlayer = GetPlayerFromString.GetPlayer(args[1]);
- if (myPlayer == null) { return new string[] { "Could not find player: " + args[1] }; ; }
+ if (!GetFromString.TryGetPlayer(args[1], out Player myPlayer))
+ return new string[] { "Could not find player: " + args[1] };
Vector myvector = myPlayer.GetPosition();
string desc = "";
if (args.Length >= 3)
for (int i = 3; i < args.Length; i++)
desc = args[i] + " ";
AdminToolbox.WarpVectorDict.Add(args[2].ToLower(), new WarpPoint { Name = args[2].ToLower(), Description = desc, Vector = new ATVector(myvector) });
- AdminToolbox.warpManager.WriteWarpsToFile();
+ AdminToolbox.WarpManager.WriteWarpsToFile();
return new string[] { "Warp point: " + args[2].ToLower() + " added." };
}
else
@@ -109,7 +108,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
return new string[] { "Teleported " + playerNum + " players to warp point: " + args[1] };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't get player: " + args[0] }; ; }
if (!AdminToolbox.WarpVectorDict.ContainsKey(args[1].ToLower()))
return new string[] { "No warp point called: " + args[1] };
diff --git a/AdminToolbox/AdminToolbox/Commands/Facility/WarpsCommand.cs b/AdminToolbox/AdminToolbox/Commands/Facility/WarpsCommand.cs
index 80ed6c5..3f484ff 100644
--- a/AdminToolbox/AdminToolbox/Commands/Facility/WarpsCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Facility/WarpsCommand.cs
@@ -17,7 +17,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (args.Length >= 1 && (args[0].ToUpper() == "R" || args[0].ToUpper() == "REFRESH"))
{
- AdminToolbox.warpManager.RefreshWarps();
+ AdminToolbox.WarpManager.RefreshWarps();
return new string[] { "Warps was refreshed!" };
}
else
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/ATBanCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/ATBanCommand.cs
index 2496449..1191257 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/ATBanCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/ATBanCommand.cs
@@ -14,7 +14,7 @@ public class ATBanCommand : ICommandHandler
private Server Server => PluginManager.Manager.Server;
public ATBanCommand(AdminToolbox plugin) => this.plugin = plugin;
- public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [NAME] [IP/UserId] ";
+ public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [NAME] [IP/UserID] ";
public string GetCommandDescription() => "Alternative ban for offline users";
public static readonly string[] CommandAliases = new string[] { "ATBAN", "OBAN", "OFFLINEBAN" };
@@ -27,7 +27,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (args.Length < 2) return new string[] { GetUsage() };
- string IssuingPlayer = (sender is Player pl && !string.IsNullOrEmpty(pl.UserId)) ? pl.Name : "Server";
+ string IssuingPlayer = (sender is Player pl && !string.IsNullOrEmpty(pl.UserID)) ? pl.Name : "Server";
string bannedPlayer = args[0];
string input = args[1];
int minutes = Config.GetIntValue("admintoolbox_atban_duration_default", 43800); //Default 4 weeks
@@ -47,7 +47,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
Player[] plist = Server.GetPlayers().ToArray();
foreach (Player player in plist)
{
- if (player.IpAddress.Contains(input))
+ if (player.IPAddress.Contains(input))
{
bannedPlayer = player.Name;
player.Ban(0, "You have been banned from this server!");
@@ -72,7 +72,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
Player[] plist = Server.GetPlayers().ToArray();
foreach (Player player in plist)
{
- if (player.UserId == sID.ToString())
+ if (player.UserID == sID.ToString())
{
bannedPlayer = player.Name;
player.Ban(0, "You have been banned from this server!");
@@ -84,7 +84,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
string response = "\n" +
"Player with name: " + bannedPlayer + "\n" +
- "UserId64: " + input.Trim() + "\n" +
+ "UserID64: " + input.Trim() + "\n" +
"Was banned for: " + minutes + " minutes \n" +
"By: " + IssuingPlayer;
@@ -93,7 +93,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
return new string[] { response };
}
else
- return new string[] { "UserId / IP not in correct format!", GetUsage() };
+ return new string[] { "UserID / IP not in correct format!", GetUsage() };
}
catch (Exception e)
{
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/BreakDoorsCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/BreakDoorsCommand.cs
index c9afea3..cb2d598 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/BreakDoorsCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/BreakDoorsCommand.cs
@@ -21,7 +21,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
- AdminToolbox.AddMissingPlayerVariables();
+ Managers.ATFile.AddMissingPlayerVariables();
if (args.Length > 0)
{
if (Utility.AllAliasWords.Contains(args[0].ToUpper()))
@@ -34,7 +34,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.destroyDoor = j;
playerNum++;
@@ -50,7 +50,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
ps.destroyDoor = !ps.destroyDoor;
}
return new string[] { "Toggled all players BreakDoors" };
@@ -62,7 +62,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps) && ps.destroyDoor)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps) && ps.destroyDoor)
myPlayerList.Add(pl.Name);
}
if (myPlayerList.Count > 0)
@@ -74,11 +74,11 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "No players with \"BreakDoors\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null && sender is Player sendingPlayer)
myPlayer = sendingPlayer;
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; }
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings psetting))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings psetting))
if (args.Length > 1)
{
if (args[1].ToLower() == "on" || args[1].ToLower() == "true") { psetting.destroyDoor = true; }
@@ -94,7 +94,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
return new string[] { myPlayer.Name + " not in dictionary" };
}
- else if (sender is Player p && AdminToolbox.ATPlayerDict.TryGetValue(p.UserId, out PlayerSettings ps))
+ else if (sender is Player p && AdminToolbox.ATPlayerDict.TryGetValue(p.UserID, out PlayerSettings ps))
{
ps.destroyDoor = !ps.destroyDoor;
return new string[] { "Toggled BreakDoors! Currently: " + ps.destroyDoor };
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/EmptyCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/EmptyCommand.cs
index 28f0b38..3d9bcea 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/EmptyCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/EmptyCommand.cs
@@ -12,8 +12,6 @@ namespace AdminToolbox.Command
public class EmptyCommand : ICommandHandler
{
- private static Map Map => PluginManager.Manager.Server.Map;
-
public string GetCommandDescription() => "Empties the player's inventory";
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [Player] (ItemType Number / Delete) ";
@@ -26,18 +24,18 @@ public class EmptyCommand : ICommandHandler
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
- Smod2.API.ItemType type = Smod2.API.ItemType.NULL;
+ Smod2.API.ItemType type = Smod2.API.ItemType.NONE;
Player player = null;
bool delete = false;
foreach (string arg in args)
{
- if (player == null && GetPlayerFromString.GetPlayer(arg) is Player p && p != null)
+ if (player == null && GetFromString.TryGetPlayer(arg, out Player p))
{
player = p;
continue;
}
- if (int.TryParse(arg, out int itemNumber))
+ if (type == Smod2.API.ItemType.NONE && int.TryParse(arg, out int itemNumber))
{
Utility.TryParseItem(itemNumber, out type);
continue;
@@ -55,26 +53,26 @@ public class EmptyCommand : ICommandHandler
}
- private string[] DropItems(Player player, Smod2.API.ItemType itemFilter = Smod2.API.ItemType.NULL, bool delete = false)
+ private string[] DropItems(Player player, Smod2.API.ItemType itemFilter = Smod2.API.ItemType.NONE, bool delete = false)
{
- Smod2.API.ItemType ammoFlag = Smod2.API.ItemType.DROPPED_5 | Smod2.API.ItemType.DROPPED_7 | Smod2.API.ItemType.DROPPED_9;
+ Smod2.API.ItemType ammoFlag = Smod2.API.ItemType.AMMO_12_GAUGE | Smod2.API.ItemType.AMMO_44_CAL | Smod2.API.ItemType.AMMO_556_X45 | Smod2.API.ItemType.AMMO_762_X39 | Smod2.API.ItemType.AMMO_9_X19;
if (player == null)
return new string[] { "Player not spesified!" };
- if (player.TeamRole.Role == Smod2.API.RoleType.UNASSIGNED)
+ if (player.PlayerRole.RoleID == Smod2.API.RoleType.NONE)
return new string[] { "Player not properly initialized!" };
- if (player.TeamRole.Role == Smod2.API.RoleType.SPECTATOR)
+ if (player.PlayerRole.RoleID == Smod2.API.RoleType.SPECTATOR)
return new string[] { "This can not be used on spectators!" };
byte itemCount = 0;
- Vector pos = player.GetPosition(), rot = player.GetRotation();
+ //Vector pos = player.GetPosition(), rot = player.GetRotation();
- if (itemFilter == Smod2.API.ItemType.NULL || !ammoFlag.HasFlag(itemFilter))
+ if (itemFilter == Smod2.API.ItemType.NONE || !ammoFlag.HasFlag(itemFilter))
{
foreach (SMItem playerItem in player.GetInventory())
{
- if (playerItem.ItemType != Smod2.API.ItemType.NULL)
- if (itemFilter == Smod2.API.ItemType.NULL || playerItem.ItemType == itemFilter)
+ if (playerItem.ItemType != Smod2.API.ItemType.NONE)
+ if (itemFilter == Smod2.API.ItemType.NONE || playerItem.ItemType == itemFilter)
{
if (delete)
playerItem.Remove();
@@ -87,20 +85,20 @@ private string[] DropItems(Player player, Smod2.API.ItemType itemFilter = Smod2.
}
- if (itemFilter == Smod2.API.ItemType.NULL || ammoFlag.HasFlag(itemFilter))
- {
- foreach (AmmoType ammo in Enum.GetValues(typeof(AmmoType)))
- {
- Smod2.API.ItemType ammoItem = ammo == Smod2.API.AmmoType.DROPPED_5 ? Smod2.API.ItemType.DROPPED_5 : ammo == Smod2.API.AmmoType.DROPPED_7 ? Smod2.API.ItemType.DROPPED_7 : Smod2.API.ItemType.DROPPED_9;
-
- if (itemFilter == Smod2.API.ItemType.NULL || ammoItem == itemFilter)
- {
- player.SetAmmo(ammo, 0);
- if (!delete)
- Map.SpawnItem(ammoItem, pos, rot);
- }
- }
- }
+ //if (itemFilter == Smod2.API.ItemType.NONE || ammoFlag.HasFlag(itemFilter))
+ //{
+ // foreach (AmmoType ammo in Enum.GetValues(typeof(AmmoType)))
+ // {
+ // Smod2.API.ItemType ammoItem = ammo == Smod2.API.AmmoType.DROPPED_5 ? Smod2.API.ItemType.DROPPED_5 : ammo == Smod2.API.AmmoType.DROPPED_7 ? Smod2.API.ItemType.DROPPED_7 : Smod2.API.ItemType.DROPPED_9;
+
+ // if (itemFilter == Smod2.API.ItemType.NONE || ammoItem == itemFilter)
+ // {
+ // player.SetAmmo(ammo, 0);
+ // if (!delete)
+ // Map.SpawnItem(ammoItem, pos, rot);
+ // }
+ // }
+ //}
return new string[] { delete ? "Deleted " : "Dropped (" + itemCount + ") items from player " + player.Name + "'s inventory" };
}
}
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/GhostCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/GhostCommand.cs
index 7ea16b6..2553618 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/GhostCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/GhostCommand.cs
@@ -10,10 +10,7 @@ namespace AdminToolbox.Command
using API.Extentions;
public class GhostCommand : ICommandHandler
{
- private readonly AdminToolbox plugin;
private Server Server => PluginManager.Manager.Server;
-
- public GhostCommand(AdminToolbox plugin) => this.plugin = plugin;
public string GetCommandDescription() => "Sets the player's visibility to other players";
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") ";
@@ -92,7 +89,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
str = "\nNo players with \"GhostMode\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; }
if (args.Length > 1)
{
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/GodModeCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/GodModeCommand.cs
index 05e736c..d76918c 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/GodModeCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/GodModeCommand.cs
@@ -23,7 +23,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
- if (sender is Player p) AdminToolbox.AddMissingPlayerVariables(new List { p });
+ if (sender is Player p) Managers.ATFile.AddMissingPlayerVariables(new List { p });
if (args.Length > 0)
{
if (Utility.AllAliasWords.Contains(args[0].ToUpper()))
@@ -38,7 +38,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.godMode = j;
if (changedState)
@@ -59,7 +59,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings psetting))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings psetting))
psetting.godMode = !psetting.godMode;
}
return new string[] { "Toggled all players AT-Godmodes" };
@@ -71,7 +71,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings plsetting) && plsetting.godMode)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings plsetting) && plsetting.godMode)
{
myPlayerList.Add(pl.Name);
//str += " - " +pl.Name + "\n";
@@ -88,9 +88,9 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "\n" + "No players with \"AT-Godmode\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) return new string[] { "Couldn't find player: " + args[0] };
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings pls))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings pls))
{
if (args.Length > 1)
{
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/GrenadeModeCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/GrenadeModeCommand.cs
index 4b6b4f5..c863e30 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/GrenadeModeCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/GrenadeModeCommand.cs
@@ -10,14 +10,8 @@ namespace AdminToolbox.Command
using API.Extentions;
public class GrenadeModeCommand : ICommandHandler
{
- private readonly AdminToolbox plugin;
-
- private static IConfigFile Config => ConfigManager.Manager.Config;
-
private Server Server => PluginManager.Manager.Server;
- public GrenadeModeCommand(AdminToolbox plugin) => this.plugin = plugin;
-
public string GetCommandDescription() => "Enableds/Disables grenademode";
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ")";
public static readonly string[] CommandAliases = new string[] { "GMODE", "GRENADEM", "GRENADEMODE", "ATGRENADE" };
@@ -35,12 +29,14 @@ public string[] OnCall(ICommandSender sender, string[] args)
case "PLAYERS":
List plNames = new List { "Players with GRENADEMODE enabled:" };
foreach (Player p in Server.GetPlayers())
- if (AdminToolbox.ATPlayerDict.TryGetValue(p.UserId, out PlayerSettings ps) && ps.grenadeMode)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(p.UserID, out PlayerSettings ps) && ps.grenadeMode)
plNames.Add(" - " + p.Name);
return plNames.ToArray();
}
+#pragma warning disable IDE0059 // Unnecessary assignment of a value
Player[] players = new Player[0];
+#pragma warning restore IDE0059 // Unnecessary assignment of a value
if (args.Length > 0 && Utility.AllAliasWords.Contains(args[0].ToUpper()))
{
players = Server.GetPlayers().ToArray();
@@ -49,17 +45,17 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
else
{
- Player p = (args.Length > 0) ? GetPlayerFromString.GetPlayer(args[0]) : sender as Player;
+ Player p = (args.Length > 0) ? GetFromString.GetPlayer(args[0]) : sender as Player;
if (p == null)
return new string[] { "Couldn't get player: " + args[0] };
players = new Player[] { p };
}
if (players.Length > 0)
{
- bool? s = (args.Length > 1 && bool.TryParse(args[1], out bool b) ? (bool?)b : null);
+ bool? s = (args.Length > 1 && bool.TryParse(args[1], out bool b)) ? (bool?)b : null;
foreach (Player pl in players)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.grenadeMode = s.HasValue ? (bool)s : !ps.grenadeMode;
}
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/HealCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/HealCommand.cs
index 72da7d5..f20adcd 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/HealCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/HealCommand.cs
@@ -26,46 +26,51 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (args.Length > 1)
{
- if (int.TryParse(args[1], out int j))
+ if (int.TryParse(args[1], out int amount))
{
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- pl.AddHealth(j);
+ pl.Health += amount;
playerNum++;
}
- if (playerNum > 1)
- return new string[] { "Added " + j + " HP to " + playerNum + " player(s)" };
- else
- return new string[] { "Added " + j + " HP to " + playerNum + " player" };
+ return new string[] { "Added " + amount + " HP to " + playerNum + " player" + (playerNum > 1 ? "s" : "") };
}
else
{
- return new string[] { "Not a valid number!" };
+ return new string[] { args[1] + " : Not a valid number!" };
}
}
else
{
- foreach (Player pl in Server.GetPlayers()) { pl.SetHealth(pl.TeamRole.MaxHP); }
- return new string[] { "Set all players to their default max HP" };
+ int count = 0;
+ foreach (Player pl in Server.GetPlayers())
+ {
+ pl.Health = pl.PlayerRole.MaxHP;
+ count++;
+ }
+ return new string[] { $"Set {count} player{(count > 1 ? "s" : "")} to their default max HP" };
}
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
- if (myPlayer == null) return new string[] { "Couldn't find player: " + args[0] };
- if (args.Length > 1)
+ if (!GetFromString.TryGetPlayer(args[0], out Player myPlayer))
+ return new string[] { "Couldn't find player: " + args[0] };
+ else
{
- if (int.TryParse(args[1], out int j))
+ if (args.Length > 1)
{
- myPlayer.AddHealth(j);
- return new string[] { "Added " + j + " HP " + " to " + myPlayer.Name };
+ if (int.TryParse(args[1], out int amount))
+ {
+ myPlayer.Health += amount;
+ return new string[] { "Added " + amount + " HP " + " to " + myPlayer.Name };
+ }
+ else
+ return new string[] { "Not a valid number!" };
}
else
- return new string[] { "Not a valid number!" };
- }
- else
- {
- myPlayer.SetHealth(myPlayer.TeamRole.MaxHP);
- return new string[] { "Set " + myPlayer.Name + " to full HP" };
+ {
+ myPlayer.Health = myPlayer.PlayerRole.MaxHP;
+ return new string[] { "Set " + myPlayer.Name + " to full HP" };
+ }
}
}
else
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/InfiniteItemCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/InfiniteItemCommand.cs
index 97599ce..300eacb 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/InfiniteItemCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/InfiniteItemCommand.cs
@@ -10,14 +10,8 @@ namespace AdminToolbox.Command
using API.Extentions;
public class InfiniteItemCommand : ICommandHandler
{
- private readonly AdminToolbox plugin;
-
- private static IConfigFile Config => ConfigManager.Manager.Config;
-
private Server Server => PluginManager.Manager.Server;
- public InfiniteItemCommand(AdminToolbox plugin) => this.plugin = plugin;
-
public string GetCommandDescription() => "This is a description";
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ")";
public static readonly string[] CommandAliases = new string[] { "INFI", "INFITEM", "INFINITEI", "INFINITEITEM" };
@@ -35,12 +29,14 @@ public string[] OnCall(ICommandSender sender, string[] args)
case "PLAYERS":
List plNames = new List { "Players with INFINITEITEM enabled:" };
foreach (Player p in Server.GetPlayers())
- if (AdminToolbox.ATPlayerDict.TryGetValue(p.UserId, out PlayerSettings ps) && ps.InfiniteItem != Smod2.API.ItemType.NULL)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(p.UserID, out PlayerSettings ps) && ps.InfiniteItem != Smod2.API.ItemType.NONE)
plNames.Add(" - " + p.Name + " -> + " + ps.InfiniteItem.ToString());
return plNames.ToArray();
}
+#pragma warning disable IDE0059 // Unnecessary assignment of a value
Player[] players = new Player[0];
+#pragma warning restore IDE0059 // Unnecessary assignment of a value
if (args.Length > 0 && Utility.AllAliasWords.Contains(args[0].ToUpper()))
{
players = Server.GetPlayers().ToArray();
@@ -49,22 +45,22 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
else
{
- Player p = (args.Length > 0) ? GetPlayerFromString.GetPlayer(args[0]) : sender as Player;
+ Player p = (args.Length > 0) ? GetFromString.GetPlayer(args[0]) : sender as Player;
if (p == null)
return new string[] { "Couldn't get player: " + args[0] };
players = new Player[] { p };
}
if (players.Length > 0)
{
- Smod2.API.ItemType item = args.Length > 1 && Utility.TryParseItem(args[1], out Smod2.API.ItemType i) ? i : Smod2.API.ItemType.NULL;
+ Smod2.API.ItemType item = args.Length > 1 && Utility.TryParseItem(args[1], out Smod2.API.ItemType i) ? i : Smod2.API.ItemType.NONE;
foreach (Player pl in players)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.InfiniteItem = item;
}
}
- return new string[] { $"Set {players.Length.ToString()} player's INFINITEITEM to {item.ToString()}" };
+ return new string[] { $"Set {players.Length.ToString()} player's INFINITEITEM to {item}" };
}
else
return new string[] { GetUsage() };
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/InstantKillCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/InstantKillCommand.cs
index b4a1190..44839bd 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/InstantKillCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/InstantKillCommand.cs
@@ -25,7 +25,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (Utility.AllAliasWords.Contains(args[0].ToUpper()))
{
- AdminToolbox.AddMissingPlayerVariables();
+ Managers.ATFile.AddMissingPlayerVariables();
if (args.Length > 1)
{
if (bool.TryParse(args[1], out bool j))
@@ -34,7 +34,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.instantKill = j;
playerNum++;
@@ -52,7 +52,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings psetting))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings psetting))
psetting.instantKill = !psetting.instantKill;
}
return new string[] { "Toggled all players InstantKill" };
@@ -60,12 +60,12 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
else if (args[0].ToLower() == "list" || args[0].ToLower() == "get")
{
- AdminToolbox.AddMissingPlayerVariables();
+ Managers.ATFile.AddMissingPlayerVariables();
string str = "\nPlayers with InstantKill enabled: \n";
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings psett) && psett.instantKill)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings psett) && psett.instantKill)
{
myPlayerList.Add(pl.Name);
//str += " - " +pl.Name + "\n";
@@ -82,26 +82,26 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "\nNo players with \"InstantKill\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
if (args.Length > 1)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings ps))
{
- if (bool.TryParse(args[1], out bool g)) AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill = g;
- else if (args[1].ToLower() == "on") { AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill = true; }
- else if (args[1].ToLower() == "off") { AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill = false; }
+ if (bool.TryParse(args[1], out bool g)) AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill = g;
+ else if (args[1].ToLower() == "on") { AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill = true; }
+ else if (args[1].ToLower() == "off") { AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill = false; }
else return new string[] { GetUsage() };
- return new string[] { myPlayer.Name + " InstantKill: " + AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill };
+ return new string[] { myPlayer.Name + " InstantKill: " + AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill };
}
else
return new string[] { myPlayer.Name + " not in dictionary" };
}
else
{
- AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill = !AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill;
- return new string[] { myPlayer.Name + " InstantKill: " + AdminToolbox.ATPlayerDict[myPlayer.UserId].instantKill };
+ AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill = !AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill;
+ return new string[] { myPlayer.Name + " InstantKill: " + AdminToolbox.ATPlayerDict[myPlayer.UserID].instantKill };
}
}
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/KeepSettingsCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/KeepSettingsCommand.cs
index fc2a0b4..ff207ad 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/KeepSettingsCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/KeepSettingsCommand.cs
@@ -33,8 +33,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(pl);
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(pl);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
ps.keepSettings = j;
playerNum++;
}
@@ -50,8 +50,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
foreach (Player pl in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(pl);
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(pl);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
ps.keepSettings = !ps.keepSettings;
}
return new string[] { "Toggled all players KeepSettings" };
@@ -63,7 +63,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps) && ps.keepSettings)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps) && ps.keepSettings)
{
myPlayerList.Add(pl.Name);
}
@@ -79,10 +79,10 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "\nNo players with \"KeepSettings\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings psett))
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings psett))
if (args.Length > 1)
{
if (args[1].ToLower() == "on" || args[1].ToLower() == "true") { psett.keepSettings = true; }
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/KillCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/KillCommand.cs
index a7e12cc..35d31b4 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/KillCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/KillCommand.cs
@@ -37,23 +37,25 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
int playerNum = 0;
- foreach (Player p in Server.GetPlayers().Where(pl => pl.PlayerId != (caller != null ? caller.PlayerId : -1)
- && !pl.GetGodmode() &&
- (AdminToolbox.ATPlayerDict.ContainsKey(pl.UserId) ? !AdminToolbox.ATPlayerDict[pl.UserId].godMode : true)
- && pl.TeamRole.Team != Smod2.API.TeamType.SPECTATOR))
+ foreach (Player p in Server.GetPlayers(pl => pl.PlayerID != (caller != null ? caller.PlayerID : -1)
+ && !pl.GodMode &&
+ (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings pSetting) ? !pSetting.godMode : true)
+ && pl.PlayerRole.Team != Smod2.API.TeamType.SPECTATOR))
{
- p.Kill(killType);
+ p.Kill(killType.ToString());
playerNum++;
}
- if (caller != null && !string.IsNullOrEmpty(caller.Name) && caller.Name.ToLower() != "server") plugin.Info(caller.Name + " ran the \"SLAY\" command on: " + playerNum + " players");
+ if (caller != null && !string.IsNullOrEmpty(caller.Name) && caller.Name.ToLower() != "server")
+ plugin.Info(caller.Name + " ran the \"SLAY\" command on: " + playerNum + " players");
return new string[] { playerNum + " players has been slain!" };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
- if (myPlayer == null) { return new string[] { "Couldn't get player: " + args[0] }; }
- if (myPlayer.TeamRole.Role != Smod2.API.RoleType.SPECTATOR)
+ if (!GetFromString.TryGetPlayer(args[0], out Player myPlayer))
+ return new string[] { "Couldn't get player: " + args[0] };
+ if (myPlayer.PlayerRole.RoleID != Smod2.API.RoleType.SPECTATOR)
{
- if (caller != null && !string.IsNullOrEmpty(caller.Name) && caller.Name.ToLower() != "server") plugin.Info(caller.Name + " ran the \"SLAY\" command on: " + myPlayer.Name);
- myPlayer.Kill(killType);
+ if (caller != null && !string.IsNullOrEmpty(caller.Name) && caller.Name.ToLower() != "server")
+ plugin.Info(caller.Name + " ran the \"SLAY\" command on: " + myPlayer.Name);
+ myPlayer.Kill(killType.ToString());
return new string[] { myPlayer.Name + " has been slain!" };
}
else
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/LockDoorsCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/LockDoorsCommand.cs
index 934c650..3cdbbd5 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/LockDoorsCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/LockDoorsCommand.cs
@@ -11,12 +11,8 @@ namespace AdminToolbox.Command
public class LockDoorsCommand : ICommandHandler
{
- private readonly AdminToolbox plugin;
-
- private static IConfigFile Config => ConfigManager.Manager.Config;
private Server Server => PluginManager.Manager.Server;
- public LockDoorsCommand(AdminToolbox plugin) => this.plugin = plugin;
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") ";
public string GetCommandDescription() => "Makes the user able to lock doors interacted with";
@@ -32,7 +28,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings psetting) && psetting.lockDoors)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings psetting) && psetting.lockDoors)
myPlayerList.Add(pl.Name);
}
if (myPlayerList.Count > 0)
@@ -45,7 +41,9 @@ public string[] OnCall(ICommandSender sender, string[] args)
return new string[] { str };
}
+#pragma warning disable IDE0059 // Unnecessary assignment of a value
Player[] players = new Player[0];
+#pragma warning restore IDE0059 // Unnecessary assignment of a value
bool? enabled = null;
if (args.Length > 0 && bool.TryParse(args[0], out bool b1))
@@ -61,7 +59,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
else
{
- Player p = (args.Length > 0) ? GetPlayerFromString.GetPlayer(args[0]) : sender as Player;
+ Player p = (args.Length > 0) ? GetFromString.GetPlayer(args[0]) : sender as Player;
if (p == null)
return new string[] { "Couldn't get player: " + args[0] };
players = new Player[] { p };
@@ -71,7 +69,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
int pcount = 0;
foreach (Player pl in players)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
pcount++;
if (enabled.HasValue)
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/LockdownCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/LockdownCommand.cs
index d531dc8..de3d9a5 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/LockdownCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/LockdownCommand.cs
@@ -33,8 +33,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(pl);
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(pl);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.lockDown = j;
playerNum++;
@@ -50,8 +50,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
foreach (Player pl in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(pl);
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(pl);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
ps.lockDown = !ps.lockDown;
}
return new string[] { "Toggled all players Lockdown" };
@@ -63,7 +63,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings pls) && pls.lockDown)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings pls) && pls.lockDown)
{
myPlayerList.Add(pl.Name);
//str += " - " +pl.Name + "\n";
@@ -80,10 +80,10 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "\nNo players with \"LockDown\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings psetting))
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings psetting))
if (args.Length > 1)
{
if (bool.TryParse(args[1], out bool g)) psetting.lockDown = g;
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/NoDmgCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/NoDmgCommand.cs
index 2484053..3c8674a 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/NoDmgCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/NoDmgCommand.cs
@@ -33,8 +33,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(pl);
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(pl);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
{
ps.dmgOff = j;
playerNum++;
@@ -49,8 +49,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
foreach (Player pl in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(pl);
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(pl);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings ps))
ps.dmgOff = !ps.dmgOff;
}
return new string[] { "Toggled all player's \"No Dmg\"" };
@@ -62,7 +62,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings pls) && pls.dmgOff)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings pls) && pls.dmgOff)
myPlayerList.Add(pl.Name);
}
if (myPlayerList.Count > 0)
@@ -76,10 +76,10 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "\nNo players with \"No Dmg\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't get player: " + args[0] }; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings psetting))
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings psetting))
if (args.Length > 1)
{
bool changedValue = false;
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/PlayerCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/PlayerCommand.cs
index 179c5a0..badcfa2 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/PlayerCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/PlayerCommand.cs
@@ -15,7 +15,7 @@ public class PlayerCommand : ICommandHandler
private Server Server => PluginManager.Manager.Server;
public string GetCommandDescription() => "Gets toolbox info about spesific player";
- public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [PLAYERNAME/ID/UserId]";
+ public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [PLAYERNAME/ID/UserID]";
public static readonly string[] CommandAliases = new string[] { "PLAYER", "P", "PLAYERINFO", "PINFO" };
@@ -40,7 +40,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (Server.GetPlayers().Count > 0)
{
- Player myPlayer = (args.Length > 0) ? GetPlayerFromString.GetPlayer(args[0]) : null;
+ Player myPlayer = (args.Length > 0) ? GetFromString.GetPlayer(args[0]) : null;
if (myPlayer == null && sender is Player sendingPlayer)
myPlayer = sendingPlayer;
else if (myPlayer == null)
@@ -50,29 +50,29 @@ public string[] OnCall(ICommandSender sender, string[] args)
return new string[] { GetUsage() };
//Handling player stats
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
- AdminToolbox.atfileManager.PlayerStatsFileManager(myPlayer.UserId, Managers.ATFileManager.PlayerFile.Write);
- PlayerSettings playerDict = AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings ps) ? ps : new PlayerSettings(myPlayer.UserId);
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
+ AdminToolbox.FileManager.PlayerStatsFileManager(myPlayer.UserID, Managers.ATFile.PlayerFile.Write);
+ PlayerSettings playerDict = AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings ps) ? ps : new PlayerSettings(myPlayer.UserID);
//Inventory
string playerInv = string.Empty;
- foreach (SMItem i in myPlayer.GetInventory().Where(i => i.ItemType != Smod2.API.ItemType.NULL))
+ foreach (SMItem i in myPlayer.GetInventory().Where(i => i.ItemType != Smod2.API.ItemType.NONE))
playerInv += i.ItemType + ", ";
if (playerInv == string.Empty) playerInv = "Empty Inventory";
//Calculating remaining jail time
- int remainingJailTime = ((int)playerDict.JailedToTime.Subtract(DateTime.Now).TotalSeconds >= 0) ? (int)playerDict.JailedToTime.Subtract(DateTime.Now).TotalSeconds : 0;
+ int remainingJailTime = ((int)playerDict.JailedToTime.Subtract(DateTime.UtcNow).TotalSeconds >= 0) ? (int)playerDict.JailedToTime.Subtract(DateTime.UtcNow).TotalSeconds : 0;
- string _playerRole = sender.IsPlayer() ? myPlayer.ToColoredRichTextRole() : Smod2.API.RoleType.UNASSIGNED + "";
+ string _playerRole = sender.IsPlayer() ? myPlayer.ToColoredRichTextRole() : Smod2.API.RoleType.NONE + "";
string _roleColor = myPlayer.GetUserGroup().Color ?? "default";
string _serverRole = myPlayer.GetRankName() ?? "";
//Building string
string playerInfoString = Environment.NewLine + Environment.NewLine +
- "Player: (" + myPlayer.PlayerId + ") " + myPlayer.Name + Environment.NewLine +
- BuildTwoLiner(" - UserId: " + myPlayer.UserId, " - IP: " + myPlayer.IpAddress.Replace("::ffff:", string.Empty)) + Environment.NewLine +
+ "Player: (" + myPlayer.PlayerID + ") " + myPlayer.Name + Environment.NewLine +
+ BuildTwoLiner(" - UserID: " + myPlayer.UserID, " - IP: " + myPlayer.IPAddress.Replace("::ffff:", string.Empty)) + Environment.NewLine +
BuildTwoLiner(" - Server Rank: " + "" + _serverRole + "") + Environment.NewLine +
- BuildTwoLiner(" - Role: " + _playerRole, " - Health: " + myPlayer.GetHealth()) + Environment.NewLine +
+ BuildTwoLiner(" - Role: " + _playerRole, " - Health: " + myPlayer.Health) + Environment.NewLine +
BuildTwoLiner(" - AdminToolbox Toggables: ") + Environment.NewLine +
BuildTwoLiner(" - Godmode: " + playerDict.godMode, " - NoDmg: " + playerDict.dmgOff) + Environment.NewLine +
BuildTwoLiner(" - OverwatchMode: " + myPlayer.OverwatchMode, " - KeepSettings: " + playerDict.keepSettings) + Environment.NewLine +
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/PosCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/PosCommand.cs
index 808f55b..ccbcbc6 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/PosCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/PosCommand.cs
@@ -23,9 +23,9 @@ public string[] OnCall(ICommandSender sender, string[] args)
if (args.Length > 0)
{
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; ; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
if (args.Length > 1)
{
if (args.Length > 2)
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/RoleCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/RoleCommand.cs
index 70db2b3..e0c9e4c 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/RoleCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/RoleCommand.cs
@@ -26,23 +26,23 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (args.Length > 1)
{
- if (int.TryParse(args[1], out int j) && Utility.TryParseRole(j, out Smod2.API.RoleType spesifiedRole))
+ if (int.TryParse(args[1], out int j) && Utility.TryParseRole(j, out Smod2.API.RoleType specifiedRole))
{
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
Vector originalPos = pl.GetPosition();
- if (pl.TeamRole.Role == Smod2.API.RoleType.UNASSIGNED || pl.TeamRole.Role == Smod2.API.RoleType.SPECTATOR)
- pl.ChangeRole(spesifiedRole, true, true);
+ if (pl.PlayerRole.RoleID == Smod2.API.RoleType.NONE || pl.PlayerRole.RoleID == Smod2.API.RoleType.SPECTATOR)
+ pl.ChangeRole(specifiedRole, true, true);
else
{
- pl.ChangeRole(spesifiedRole, true, false);
+ pl.ChangeRole(specifiedRole, true, false);
pl.Teleport(originalPos, true);
}
- pl.SetHealth(pl.TeamRole.MaxHP);
+ pl.Health = pl.PlayerRole.MaxHP;
playerNum++;
}
- return new string[] { playerNum + " " + (playerNum > 1 ? "roles" : "role") + " set to " + spesifiedRole };
+ return new string[] { playerNum + " " + (playerNum > 1 ? "roles" : "role") + " set to " + specifiedRole };
}
else
{
@@ -54,27 +54,30 @@ public string[] OnCall(ICommandSender sender, string[] args)
return new string[] { GetUsage() };
}
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
- if (myPlayer == null) { return new string[] { "Couldn't get player: " + args[0] }; }
- if (args.Length > 1)
+ if (!GetFromString.TryGetPlayer(args[0], out Player myPlayer))
+ return new string[] { "Couldn't get player: " + args[0] };
+ else
{
- if (int.TryParse(args[1], out int j) && Utility.TryParseRole(j, out Smod2.API.RoleType spesifiedRole))
+ if (args.Length > 1)
{
- TeamRole oldRole = myPlayer.TeamRole;
- Vector originalPos = myPlayer.GetPosition();
- bool tele = myPlayer.TeamRole.Role == Smod2.API.RoleType.UNASSIGNED || myPlayer.TeamRole.Role == Smod2.API.RoleType.SPECTATOR;
- myPlayer.ChangeRole(spesifiedRole, true, tele);
- if (tele)
- myPlayer.Teleport(originalPos, true);
- myPlayer.SetHealth(myPlayer.TeamRole.MaxHP);
- return new string[] { "Changed " + myPlayer.Name + " from " + oldRole.Name + " to " + spesifiedRole };
+ if (int.TryParse(args[1], out int j) && Utility.TryParseRole(j, out Smod2.API.RoleType targetRole))
+ {
+ Smod2.API.Role oldRole = myPlayer.PlayerRole;
+ Vector originalPos = myPlayer.GetPosition();
+ bool isDead = myPlayer.PlayerRole.RoleID == Smod2.API.RoleType.NONE || myPlayer.PlayerRole.RoleID == Smod2.API.RoleType.SPECTATOR;
+ myPlayer.ChangeRole(targetRole, true, spawnTeleport: isDead);
+ if (!isDead)
+ myPlayer.Teleport(originalPos, true);
+ myPlayer.Health = myPlayer.PlayerRole.MaxHP;
+ return new string[] { "Changed " + myPlayer.Name + " from " + oldRole.Name + " to " + targetRole };
+ }
+ else
+ return new string[] { "Not a valid ID number!" };
}
else
- return new string[] { "Not a valid ID number!" };
- }
- else
- {
- return new string[] { GetUsage() };
+ {
+ return new string[] { GetUsage() };
+ }
}
}
else
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/SetHpCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/SetHpCommand.cs
index 5146bde..8d31c2a 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/SetHpCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/SetHpCommand.cs
@@ -11,7 +11,7 @@ public class SetHpCommand : ICommandHandler
{
private Server Server => PluginManager.Manager.Server;
public string GetCommandDescription() => "Sets player HP. Use int for amount";
- public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ") [PLAYER] (AMOUNT)";
+ public string GetUsage() => $"[{string.Join(" / ", CommandAliases)}] [PLAYER] (AMOUNT)";
public static readonly string[] CommandAliases = new string[] { "ATHP", "ATSETHP", "AT-HP", "AT-SETHP" };
@@ -25,46 +25,48 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (args.Length > 1)
{
- if (int.TryParse(args[1], out int j))
+ if (int.TryParse(args[1], out int amount))
{
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- pl.SetHealth(j);
+ pl.Health = amount;
playerNum++;
}
- if (playerNum > 1)
- return new string[] { "Set " + playerNum + " players HP to " + j + "HP" };
- else
- return new string[] { "Set " + playerNum + " players HP to " + j + "HP" };
+ return new string[] { $"Set {playerNum} player{(playerNum > 1 ? "s" : "")} HP to {amount}HP" };
}
else
{
- return new string[] { "Not a valid number!" };
+ return new string[] { $"{args[1]} : Not a valid number!" };
}
}
else
{
- foreach (Player pl in Server.GetPlayers()) { pl.SetHealth(pl.TeamRole.MaxHP); }
- return new string[] { "Set all players to their default max HP" };
+ int count = 0;
+ foreach (Player pl in Server.GetPlayers())
+ {
+ pl.Health = pl.PlayerRole.MaxHP;
+ count++;
+ }
+ return new string[] { $"Set {count} player{(count > 1 ? "s" : "")} to their default max HP" };
}
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
- if (myPlayer == null) { return new string[] { "Couldn't get player: " + args[0] }; ; }
+ if (!GetFromString.TryGetPlayer(args[0], out Player myPlayer))
+ return new string[] { "Couldn't get player: " + args[0] };
if (args.Length > 1)
{
- if (int.TryParse(args[1], out int j))
+ if (int.TryParse(args[1], out int amount))
{
- myPlayer.SetHealth(j);
- return new string[] { "Set " + myPlayer.Name + "'s HP to " + j + "HP" };
+ myPlayer.Health = amount;
+ return new string[] { $"Set {myPlayer.Name}'s HP to {amount}HP" };
}
else
- return new string[] { "Not a valid number!" };
+ return new string[] { $"{args[1]} : Not a valid number!" };
}
else
{
- myPlayer.SetHealth(myPlayer.TeamRole.MaxHP);
- return new string[] { "Set " + myPlayer.Name + " to default (" + myPlayer.TeamRole.MaxHP + ") HP" };
+ myPlayer.Health = myPlayer.PlayerRole.MaxHP;
+ return new string[] { $"Set {myPlayer.Name} to default ({myPlayer.PlayerRole.MaxHP }) HP" };
}
}
else
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/SpectatorCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/SpectatorCommand.cs
index 6b76df0..b1bc0c5 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/SpectatorCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/SpectatorCommand.cs
@@ -31,8 +31,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player player in Server.GetPlayers())
{
- AdminToolbox.AddMissingPlayerVariables(player);
- if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserId, out PlayerSettings ps))
+ Managers.ATFile.AddMissingPlayerVariables(player);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserID, out PlayerSettings ps))
{
ps.overwatchMode = j;
player.OverwatchMode = j;
@@ -52,7 +52,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
int playerNum = 0;
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings plsett))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings plsett))
{
plsett.overwatchMode = !plsett.overwatchMode;
pl.OverwatchMode = !pl.OverwatchMode;
@@ -68,7 +68,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in Server.GetPlayers())
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserId, out PlayerSettings plsett) && plsett.overwatchMode)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(pl.UserID, out PlayerSettings plsett) && plsett.overwatchMode)
myPlayerList.Add(pl.Name);
}
if (myPlayerList.Count > 0)
@@ -80,10 +80,10 @@ public string[] OnCall(ICommandSender sender, string[] args)
else str = "\nNo players with \"Overwatch\" enabled!";
return new string[] { str };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; }
- AdminToolbox.AddMissingPlayerVariables(myPlayer);
- if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserId, out PlayerSettings psetting))
+ Managers.ATFile.AddMissingPlayerVariables(myPlayer);
+ if (AdminToolbox.ATPlayerDict.TryGetValue(myPlayer.UserID, out PlayerSettings psetting))
if (args.Length > 1)
{
if (args[1].ToLower() == "on" || args[1].ToLower() == "true") { psetting.overwatchMode = true; myPlayer.OverwatchMode = true; }
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/TeleportCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/TeleportCommand.cs
index cb099d0..7dae07d 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/TeleportCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/TeleportCommand.cs
@@ -24,12 +24,12 @@ public string[] OnCall(ICommandSender sender, string[] args)
if (Utility.AllAliasWords.Contains(args[0].ToUpper()))
{
int playerNum = -1;
- Player myTpPlayer = GetPlayerFromString.GetPlayer(args[1]);
+ Player myTpPlayer = GetFromString.GetPlayer(args[1]);
if (myTpPlayer == null) { return new string[] { "Couldn't find player: " + args[1] }; ; }
Vector pos = myTpPlayer.GetPosition();
foreach (Player pl in Server.GetPlayers())
{
- if (pl.PlayerId != myTpPlayer.PlayerId)
+ if (pl.PlayerID != myTpPlayer.PlayerID)
{
pl.Teleport(pos, true);
playerNum++;
@@ -37,9 +37,9 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
return new string[] { "Teleported " + playerNum + " players to " + myTpPlayer.Name };
}
- Player myPlayer = GetPlayerFromString.GetPlayer(args[0]);
+ Player myPlayer = GetFromString.GetPlayer(args[0]);
if (myPlayer == null) { return new string[] { "Couldn't find player: " + args[0] }; ; }
- Player myPlayer2 = GetPlayerFromString.GetPlayer(args[1]);
+ Player myPlayer2 = GetFromString.GetPlayer(args[1]);
if (myPlayer2 == null) { return new string[] { "Couldn't find player: " + args[1] }; ; }
if (args[1] != null)
{
diff --git a/AdminToolbox/AdminToolbox/Commands/Player/TutorialCommand.cs b/AdminToolbox/AdminToolbox/Commands/Player/TutorialCommand.cs
index 0ab880d..c566466 100644
--- a/AdminToolbox/AdminToolbox/Commands/Player/TutorialCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Player/TutorialCommand.cs
@@ -30,7 +30,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
}
else
{
- Player p = (args.Length > 0) ? GetPlayerFromString.GetPlayer(args[0]) : sender as Player;
+ Player p = (args.Length > 0) ? GetFromString.GetPlayer(args[0]) : sender as Player;
if (p == null)
return new string[] { "Couldn't get player: " + args[0] };
players = new Player[] { p };
@@ -41,10 +41,10 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (pl == null) continue;
Vector originalPos2 = pl.GetPosition();
- Vector newPos2 = pl.TeamRole.Role == Smod2.API.RoleType.SPECTATOR ? AdminToolbox.WarpVectorDict.TryGetVector("tutorial", out Vector vector2) ? vector2 : null : originalPos2;
+ Vector newPos2 = pl.PlayerRole.RoleID == Smod2.API.RoleType.SPECTATOR ? AdminToolbox.WarpVectorDict.TryGetVector("tutorial", out Vector vector2) ? vector2 : null : originalPos2;
pl.ChangeRole(Smod2.API.RoleType.TUTORIAL, spawnTeleport: newPos2 == null, removeHandcuffs: true);
if (newPos2 != null)
- AdminToolbox.waitForTeleports.Add(new WaitForTeleport { Player = pl, Pos = newPos2, DateTime = DateTime.Now.AddSeconds(1) });
+ AdminToolbox.waitForTeleports.Add(new WaitForTeleport { Player = pl, Pos = newPos2, DateTime = DateTime.UtcNow.AddSeconds(1) });
}
return new string[] { $"Set {(players.Length > 1 ? players.Length.ToString() + " players roles " : (players?[0]?.Name ?? "1 player") + "'s role ")}) to {Smod2.API.RoleType.TUTORIAL}" };
}
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/ATColorCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/ATColorCommand.cs
index ae4c194..6094b45 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/ATColorCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/ATColorCommand.cs
@@ -19,7 +19,6 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
- Server server = PluginManager.Manager.Server;
if (args.Length >= 1)
{
if (bool.TryParse(args[0], out bool x))
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/ATCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/ATCommand.cs
index 2f41ec1..1edf9ff 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/ATCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/ATCommand.cs
@@ -1,15 +1,23 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
using Smod2;
using Smod2.API;
using Smod2.Commands;
+using SMRoleType = Smod2.API.RoleType;
+using SMItemType = Smod2.API.ItemType;
namespace AdminToolbox.Command
{
+ using API;
using API.Extentions;
+ using API.Webhook;
public class ATCommand : ICommandHandler
{
private readonly AdminToolbox plugin;
private static ICommandManager CommandManager => PluginManager.Manager.CommandManager;
+ private static IConfigFile Config => ConfigManager.Manager.Config;
public ATCommand(AdminToolbox plugin) => this.plugin = plugin;
public string GetCommandDescription() => "Command with sub-commands";
@@ -21,6 +29,8 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
+ if (sender != null && sender is Player pl)
+ plugin.Info($"Player \"{pl.Name}\" used the command: " + CommandAliases[0] + " " + (args.Length > 0 ? string.Join(" ", args) : ""));
if (args.Length > 0)
{
switch (args[0].ToUpper())
@@ -33,26 +43,81 @@ public string[] OnCall(ICommandSender sender, string[] args)
case "V":
case "INFO":
case "I":
- return new string[] { "[AdminToolbox Info]", "Your Local Version: " + plugin.Details.version, "Latest GitHub Version: " + plugin.GetGitReleaseInfo().Version };
+ return new string[] { "[AdminToolbox Info]",
+ "Your Local Version: " + plugin.Details.version + (string.IsNullOrEmpty(AdminToolbox.SModLetter) ? "" : " ("+ AdminToolbox.SModLetter + ")"),
+ "Latest GitHub Version: " + ATWeb.LatestRelease.Version,
+ "Your SMod Version: " + PluginManager.GetSmodVersion() };
- case "DOWNLOAD" when !(sender is Player) || (sender is Player p && p.IpAddress == plugin.Server.IpAddress):
- case "DL" when !(sender is Player) || (sender is Player p2 && p2.IpAddress == plugin.Server.IpAddress):
+ case "DOWNLOAD" when !(sender is Player) || (sender is Player p && p.IPAddress == plugin.Server.IpAddress):
+ case "DL" when !(sender is Player) || (sender is Player p2 && p2.IPAddress == plugin.Server.IpAddress):
try
{
- System.Diagnostics.Process.Start(plugin.GetGitReleaseInfo().DownloadLink);
+ System.Diagnostics.Process.Start(ATWeb.LatestRelease.DownloadLink);
return new string[] { "Opening browser..." };
}
catch
{
- return new string[] { "Failed to open browser! Please visit GitHub or use \"AT_AutoUpdate.bat\" instead" };
+ return new string[] { $"Failed to open browser! Please run \"AT_AutoUpdate.bat\" or visit GitHub: {ATWeb.LatestRelease.DownloadLink}" };
}
+ case "WEBH":
+ case "WEBHOOK":
+ string[] banWebhookUrls = Config.GetListValue("admintoolbox_ban_webhooks", new string[0]);
+ if (banWebhookUrls.Length > 0)
+ {
+ List x = new List();
+ foreach (string url in banWebhookUrls)
+ {
+ string st = ATWeb.SendWebhook(Utility.BuildBanWebhook(null, 0, "TEST", sender is Player p ? p.Name : "Server"), url);
+ if (!string.IsNullOrEmpty(st))
+ x.Add(st);
+ }
+
+ if (x.Count > 0)
+ return x.Prepend("Webhook reply: ").ToArray();
+ else
+ return new string[] { "Webhook sent!" };
+ }
+ return new string[] { "admintoolbox_ban_webhooks config empty!" };
case "DEBUG":
if (!sender.IsPermitted(new string[] { "ATDEBUG" }, true, out string[] denied))
return denied;
AdminToolbox.DebugMode = !AdminToolbox.DebugMode;
return new string[] { "AdminToolbox Debugmode: " + AdminToolbox.DebugMode };
+ case "ITEMS":
+ Dictionary dict = new Dictionary();
+ string str = "Items:";
+ foreach (SMItemType i in Enum.GetValues(typeof(SMItemType)))
+ {
+ if (!dict.ContainsKey((int)i))
+ {
+ dict.Add((int)i, i.ToString());
+ }
+ }
+ foreach(KeyValuePair kvp in dict.OrderBy(s => s.Key))
+ str += "\n" + kvp.Key + " - " + kvp.Value;
+ return new string[] { str };
+ case "ROLES":
+ Dictionary dict2 = new Dictionary();
+ string str2 = "Roles:";
+ foreach (SMRoleType i in Enum.GetValues(typeof(SMRoleType)))
+ {
+ if (!dict2.ContainsKey((int)i))
+ {
+ dict2.Add((int)i, i.ToString());
+ }
+ }
+ foreach (KeyValuePair kvp in dict2.OrderBy(s => s.Key))
+ str2 += "\n" + kvp.Key + " - " + kvp.Value;
+ return new string[] { str2 };
+ case "ROOMS":
+ string res = "Room IDs: ";
+ foreach(string s in UnityEngine.GameObject.FindGameObjectsWithTag("RoomID").Select(s => s.GetComponent().id))
+ {
+ res += "\n - " + s;
+ }
+ return new string[] { res };
default:
return new string[] { args[0] + " is not a valid arguement!", GetUsage() };
}
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/AT_HelpCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/AT_HelpCommand.cs
index 13a2d4e..fbd5fe1 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/AT_HelpCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/AT_HelpCommand.cs
@@ -15,7 +15,7 @@ public class AT_HelpCommand : ICommandHandler
public string[] OnCall(ICommandSender sender, string[] args)
{
- if (!(sender is Player p) || (p.IpAddress == Server.IpAddress))
+ if (!(sender is Player p) || (p.IPAddress == Server.IpAddress))
{
try
{
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/PlayerListCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/PlayerListCommand.cs
index d00e83b..ae10061 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/PlayerListCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/PlayerListCommand.cs
@@ -26,7 +26,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
List myPlayerList = new List();
foreach (Player pl in players)
{
- myPlayerList.Add(pl.TeamRole.Role + "(" + (int)pl.TeamRole.Role + ")" + " " + pl.Name + " IP: " + pl.IpAddress + " USERID: " + pl.UserId + "\n");
+ myPlayerList.Add(pl.PlayerRole.RoleID + "(" + (int)pl.PlayerRole.RoleID + ")" + " " + pl.Name + " IP: " + pl.IPAddress + " UserID: " + pl.UserID + "\n");
}
myPlayerList.Sort();
foreach (string item in myPlayerList)
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/RespawnLockCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/RespawnLockCommand.cs
index aba20c9..34e33ab 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/RespawnLockCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/RespawnLockCommand.cs
@@ -6,7 +6,7 @@ namespace AdminToolbox.Command
public class RespawnLockCommand : ICommandHandler
{
public string GetCommandDescription() => "Keeps players from spawning";
- public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ")";
+ public string GetUsage() => $"({string.Join(" / ", CommandAliases)})";
public static readonly string[] CommandAliases = new string[] { "RESPAWNLOCK", "RSL", "RSPL" };
public string[] OnCall(ICommandSender sender, string[] args)
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/RoundLockCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/RoundLockCommand.cs
index 37fe0d4..b7453d6 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/RoundLockCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/RoundLockCommand.cs
@@ -9,10 +9,6 @@ public class RoundLockCommand : ICommandHandler
{
private readonly AdminToolbox plugin;
- private static IConfigFile Config => ConfigManager.Manager.Config;
-
- private Server Server => PluginManager.Manager.Server;
-
public RoundLockCommand(AdminToolbox plugin) => this.plugin = plugin;
public string GetCommandDescription() => "Forces the round to never end";
diff --git a/AdminToolbox/AdminToolbox/Commands/Server/ServerStatsCommand.cs b/AdminToolbox/AdminToolbox/Commands/Server/ServerStatsCommand.cs
index 1547311..b71c89a 100644
--- a/AdminToolbox/AdminToolbox/Commands/Server/ServerStatsCommand.cs
+++ b/AdminToolbox/AdminToolbox/Commands/Server/ServerStatsCommand.cs
@@ -8,16 +8,9 @@
namespace AdminToolbox.Command
{
using API.Extentions;
+
public class ServerStatsCommand : ICommandHandler
{
- private readonly AdminToolbox plugin;
-
- private static IConfigFile Config => ConfigManager.Manager.Config;
-
- private Server Server => PluginManager.Manager.Server;
-
- public ServerStatsCommand(AdminToolbox plugin) => this.plugin = plugin;
-
public string GetCommandDescription() => "Gets the server's round stats since last server restart";
public string GetUsage() => "(" + string.Join(" / ", CommandAliases) + ")";
@@ -27,13 +20,7 @@ public string[] OnCall(ICommandSender sender, string[] args)
{
if (sender.IsPermitted(CommandAliases, out string[] deniedReply))
{
- string reply = Environment.NewLine + " ";
- foreach (FieldInfo field in AdminToolbox.roundStats.GetType().GetFields()
- .OrderBy(s => s.GetValue(AdminToolbox.roundStats)).ThenBy(s => s.Name))
- {
- reply += "\n - " + field.Name.Replace("_", " ") + ": " + field.GetValue(AdminToolbox.roundStats) + "";
- }
- return new string[] { reply };
+ return new string[] { AdminToolbox.RoundStats.ToString() };
}
else
return deniedReply;
diff --git a/AdminToolbox/AdminToolbox/Events/LateOnCheckRoundEndEvent.cs b/AdminToolbox/AdminToolbox/Events/LateOnCheckRoundEndEvent.cs
index 9724a05..1db09c6 100644
--- a/AdminToolbox/AdminToolbox/Events/LateOnCheckRoundEndEvent.cs
+++ b/AdminToolbox/AdminToolbox/Events/LateOnCheckRoundEndEvent.cs
@@ -1,67 +1,71 @@
+using System;
+using System.Linq;
+using System.Reflection;
using Smod2.API;
using Smod2.EventHandlers;
using Smod2.Events;
namespace AdminToolbox
{
- internal class LateOnCheckRoundEndEvent : IEventHandlerCheckRoundEnd
+ public struct RoundStats
{
- private readonly AdminToolbox plugin;
-
- public LateOnCheckRoundEndEvent(AdminToolbox plugin) => this.plugin = plugin;
+ public uint Chaos_Victory { get; private set; }
+ public uint SCP_Chaos_Victory { get; private set; }
+ public uint SCP_Victory { get; private set; }
+ public uint MTF_Victory { get; private set; }
+ public uint Other_Victory { get; private set; }
+ public uint No_Victory { get; private set; }
+ public uint Forced_Round_End { get; private set; }
- private ATRoundStats Roundstats => AdminToolbox.roundStats;
-
- public void OnCheckRoundEnd(CheckRoundEndEvent ev)
- {
- if (ev.Status != ROUND_END_STATUS.ON_GOING)
- if (!AdminToolbox.roundStatsRecorded && ev.Round.Duration >= 3)
- {
- AdminToolbox.roundStatsRecorded = true;
- Roundstats.AddPoint(ev.Status);
- }
- }
- }
-
-#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
- public class ATRoundStats
- {
- public uint
- Chaos_Victory = 0,
- SCP_Chaos_Victory = 0,
- SCP_Victory = 0,
- MTF_Victory = 0,
- Other_Victory = 0,
- No_Victory = 0,
- Forced_Round_End = 0;
-
- public void AddPoint(ROUND_END_STATUS status)
+ public void AddPoint(RoundEndStatus status)
{
switch (status)
{
- case ROUND_END_STATUS.CI_VICTORY:
+ case RoundEndStatus.CI_VICTORY:
this.Chaos_Victory++;
break;
- case ROUND_END_STATUS.SCP_CI_VICTORY:
+ case RoundEndStatus.SCP_CI_VICTORY:
this.SCP_Chaos_Victory++;
break;
- case ROUND_END_STATUS.SCP_VICTORY:
+ case RoundEndStatus.SCP_VICTORY:
this.SCP_Victory++;
break;
- case ROUND_END_STATUS.MTF_VICTORY:
+ case RoundEndStatus.MTF_VICTORY:
this.MTF_Victory++;
break;
- case ROUND_END_STATUS.OTHER_VICTORY:
+ case RoundEndStatus.OTHER_VICTORY:
this.Other_Victory++;
break;
- case ROUND_END_STATUS.NO_VICTORY:
+ case RoundEndStatus.NO_VICTORY:
this.No_Victory++;
break;
- case ROUND_END_STATUS.FORCE_END:
+ case RoundEndStatus.FORCE_END:
this.Forced_Round_End++;
break;
}
}
+
+ public override string ToString()
+ {
+ string reply = Environment.NewLine + "Round Stats: ";
+ foreach (PropertyInfo property in this.GetType().GetProperties().OrderBy(s => s.Name))
+ reply += Environment.NewLine + " - " + property.Name.Replace("_", " ") + ": " + property.GetValue(this) + "";
+ return reply;
+ }
+ }
+
+ internal class LateOnCheckRoundEndEvent : IEventHandlerCheckRoundEnd
+ {
+ private RoundStats Roundstat => AdminToolbox.RoundStats;
+
+ public void OnCheckRoundEnd(CheckRoundEndEvent ev)
+ {
+ if (ev.Status != RoundEndStatus.ON_GOING)
+ if (!AdminToolbox.roundStatsRecorded && ev.Round.Duration >= 3)
+ {
+ AdminToolbox.roundStatsRecorded = true;
+ Roundstat.AddPoint(ev.Status);
+ }
+ }
}
-#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
diff --git a/AdminToolbox/AdminToolbox/Events/MyMiscEvents.cs b/AdminToolbox/AdminToolbox/Events/MyMiscEvents.cs
index 2af7bbb..ece5f7f 100644
--- a/AdminToolbox/AdminToolbox/Events/MyMiscEvents.cs
+++ b/AdminToolbox/AdminToolbox/Events/MyMiscEvents.cs
@@ -18,18 +18,18 @@ namespace AdminToolbox
internal class MyMiscEvents : IEventHandlerIntercom, IEventHandlerDoorAccess, IEventHandlerSpawn,
IEventHandlerWaitingForPlayers, IEventHandlerAdminQuery, IEventHandlerLure, IEventHandlerContain106,
IEventHandlerPlayerJoin, IEventHandlerUpdate, IEventHandlerWarheadStartCountdown, IEventHandlerSetServerName,
- IEventHandlerHandcuffed, IEventHandlerBan, IEventHandlerSetRole, IEventHandlerTeamRespawn, IEventHandlerThrowGrenade,
+ IEventHandlerHandcuffed, IEventHandlerBan, IEventHandlerTeamRespawn, IEventHandlerThrowGrenade,
IEventHandlerPlayerDropItem, IEventHandlerReload
{
private readonly AdminToolbox plugin;
private static IConfigFile Config => ConfigManager.Manager.Config;
- private Server Server => PluginManager.Manager.Server;
private Dictionary Dict => AdminToolbox.ATPlayerDict;
public MyMiscEvents(AdminToolbox plugin) => this.plugin = plugin;
private void Debug(string str) => plugin.Debug("[MiscEvents]: " + str);
+ private void Info(string str) => plugin.Info("[MiscEvents]: " + str);
public void OnIntercom(PlayerIntercomEvent ev)
{
@@ -38,58 +38,84 @@ public void OnIntercom(PlayerIntercomEvent ev)
Debug("IntercomLock active, denied use.");
ev.SpeechTime = 0f;
}
+ if (ev == null || ev.Player == null)
+ {
+ Debug("Intercom event or event-player was null!");
+ return;
+ }
#region Blacklist
- string[] blackListedUserIdS = ConfigManager.Manager.Config.GetListValue("admintoolbox_intercom_UserId_blacklist", new string[] { string.Empty }, false);
- if (blackListedUserIdS.Length > 0)
- foreach (string item in blackListedUserIdS)
- if (item == ev.Player.UserId)
- {
- Debug($"Player \"{ev.Player.Name}\" found in intercom blacklist, denied use.");
- ev.SpeechTime = 0f;
- break;
- }
+ try
+ {
+ string[] blackListedUserIDS = ConfigManager.Manager.Config.GetListValue("admintoolbox_intercom_UserID_blacklist", new string[0], false);
+ if (blackListedUserIDS.Length > 0)
+ foreach (string item in blackListedUserIDS)
+ if (item == ev.Player.UserID)
+ {
+ Debug($"Player \"{ev.Player.Name}\" found in intercom blacklist, denied use.");
+ ev.SpeechTime = 0f;
+ break;
+ }
+ }
+ catch (Exception e)
+ {
+ plugin.Info($"Exception during Intercom Blacklist: " + e);
+ }
#endregion
#region IntercomWhitelist
- string[] whitelistRanks = Config.GetListValue("admintoolbox_intercom_whitelist", new string[] { string.Empty }, false);
- if (whitelistRanks.Length > 0)
+ try
{
- foreach (string item in whitelistRanks)
+ string[] whitelistRanks = Config.GetListValue("admintoolbox_intercom_whitelist", new string[0], false);
+ if (whitelistRanks.Length > 0)
{
- string[] myKeyString = item.Split(':', '-', '_', '#');
- if (myKeyString[0].ToLower().Trim() == ev.Player.GetRankName().ToLower().Trim() || myKeyString[0].ToLower().Trim() == ev.Player.GetUserGroup().Name.ToLower().Trim())
+ foreach (string item in whitelistRanks)
{
- if (myKeyString.Length >= 2)
+ string[] myKeyString = item.Split(':', '-', '_', '#');
+ if (myKeyString[0].ToLower().Trim() == ev.Player.GetRankName().ToLower().Trim() || myKeyString[0].ToLower().Trim() == ev.Player.GetUserGroup().Name.ToLower().Trim())
{
- if (float.TryParse(myKeyString[1], out float x))
- ev.SpeechTime = (x <= 0) ? 300 : x;
- else plugin.Info(myKeyString[1] + " is not a valid speakTime number in: " + myKeyString[0]);
- if (myKeyString.Length == 3)
- if (float.TryParse(myKeyString[2], out float z))
- ev.CooldownTime = z;
- else plugin.Info(myKeyString[2] + " is not a cooldown number in: " + myKeyString[0]);
- else if (myKeyString.Length > 3)
- plugin.Error("Unknown values at \"admintoolbox_intercom_whitelist: " + item + "\", skipping...");
+ if (myKeyString.Length >= 2)
+ {
+ if (float.TryParse(myKeyString[1], out float x))
+ ev.SpeechTime = (x <= 0) ? 300 : x;
+ else plugin.Info(myKeyString[1] + " is not a valid speakTime number in: " + myKeyString[0]);
+ if (myKeyString.Length == 3)
+ if (float.TryParse(myKeyString[2], out float z))
+ ev.CooldownTime = z;
+ else plugin.Info(myKeyString[2] + " is not a cooldown number in: " + myKeyString[0]);
+ else if (myKeyString.Length > 3)
+ plugin.Error("Unknown values at \"admintoolbox_intercom_whitelist: " + item + "\", skipping...");
+ }
}
}
}
}
+ catch (Exception e)
+ {
+ plugin.Info($"Exception during Intercom Whitelist: " + e);
+ }
#endregion
- string intercomTransmit = Config.GetStringValue("admintoolbox_intercomtransmit_text", string.Empty);
- if (intercomTransmit != string.Empty && ev.SpeechTime > 0f)
- {
- if (ev.Player.GetRankName() != null && !ev.Player.GetUserGroup().Cover)
- intercomTransmit = intercomTransmit.Replace("$playerrank", ev.Player.GetRankName());
- if (ev.Player.GetUserGroup().BadgeText != null && !ev.Player.GetUserGroup().Cover)
- intercomTransmit = intercomTransmit.Replace("$playerbadge", ev.Player.GetUserGroup().BadgeText);
- intercomTransmit = intercomTransmit
- .Replace("$playerid", ev.Player.PlayerId.ToString())
- .Replace("$playerrole", ev.Player.TeamRole.Role.ToString())
- .Replace("$playerteam", ev.Player.TeamRole.Team.ToString())
- .Replace("$playerhp", ev.Player.GetHealth().ToString())
- .Replace("$playerhealth", ev.Player.GetHealth().ToString())
- .Replace("$player", ev.Player.Name)
- .Replace("\n", Environment.NewLine);
- plugin.Server.Map.SetIntercomContent(IntercomStatus.Transmitting, intercomTransmit);
+ try
+ {
+ string intercomTransmit = Config.GetStringValue("admintoolbox_intercomtransmit_text", string.Empty);
+ if (!string.IsNullOrEmpty(intercomTransmit) && ev.SpeechTime > 0f)
+ {
+ if (ev.Player.GetRankName() != null && !ev.Player.GetUserGroup().Cover)
+ intercomTransmit = intercomTransmit.Replace("$playerrank", ev.Player.GetRankName());
+ if (ev.Player.GetUserGroup().BadgeText != null && !ev.Player.GetUserGroup().Cover)
+ intercomTransmit = intercomTransmit.Replace("$playerbadge", ev.Player.GetUserGroup().BadgeText);
+ intercomTransmit = intercomTransmit
+ .Replace("$playerid", ev.Player.PlayerID.ToString())
+ .Replace("$playerrole", ev.Player.PlayerRole.RoleID.ToString())
+ .Replace("$playerteam", ev.Player.PlayerRole.Team.ToString())
+ .Replace("$playerhp", ev.Player.Health.ToString())
+ .Replace("$playerhealth", ev.Player.Health.ToString())
+ .Replace("$player", ev.Player.Name)
+ .Replace("\n", Environment.NewLine);
+ plugin.Server.Map.SetIntercomContent(IntercomStatus.TRANSMITTING, intercomTransmit);
+ }
+ }
+ catch (Exception e)
+ {
+ plugin.Info($"Exception during Intercom Transmit Text: " + e);
}
}
@@ -97,10 +123,9 @@ public void OnDoorAccess(PlayerDoorAccessEvent ev)
{
if (ev.Player != null && ev.Player is Player player)
{
- AdminToolbox.AddMissingPlayerVariables(player);
- AdminToolbox.ATPlayerDict.TryGetValue(player.UserId, out PlayerSettings playerSetting);
+ ATFile.AddMissingPlayerVariables(player);
- if (playerSetting != null)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(player.UserID, out PlayerSettings playerSetting))
{
if (playerSetting.destroyDoor)
{
@@ -116,55 +141,30 @@ public void OnDoorAccess(PlayerDoorAccessEvent ev)
if (playerSetting.lockDoors)
{
- Debug($"Player \"{ev.Player.Name}\" lock-doors active, {(ev.Door.Locked ? "unlocking" : "locking")} {(!string.IsNullOrEmpty(ev.Door.Name) ? ev.Door.Name : "door")}...");
- ev.Door.Locked = !ev.Door.Locked;
+ Debug($"Player \"{ev.Player.Name}\" lock-doors active, {(ev.Door.IsLocked ? "unlocking" : "locking")} {(!string.IsNullOrEmpty(ev.Door.Name) ? ev.Door.Name : "door")}...");
+ ev.Door.IsLocked = !ev.Door.IsLocked;
}
}
}
}
- public void OnSetRole(PlayerSetRoleEvent ev)
- {
- //if (ev.Player.TeamRole.Role == Role.TUTORIAL)
- //{
- // Vector ppos = ev.Player.GetPosition();
- // if (Physics.Raycast(new Vector3(ppos.x + 3, ppos.y - 3, ppos.z), Vector3.down, out RaycastHit hitInfo))
- // {
- // plugin.Info(string.Format("X: {0}, Y: {1}, Z: {2}", hitInfo.transform.position.x, hitInfo.transform.position.y, hitInfo.transform.position.z));
- // if (hitInfo.collider.gameObject.name.ToLower() == "classname=brush.003")
- // {
- // Vector3 hitPos = hitInfo.transform.position;
-
- // Vector newPos = new ServerMod2.API.SmodVector(hitPos.x, hitPos.y + 10, hitPos.z);
-
- // ev.Player.Teleport(newPos);
- // }
- // else
- // plugin.Info(hitInfo.collider.gameObject.name);
- // }
- // else
- // plugin.Info("No hit!");
- //}
- } //Currently not used
-
public void OnSpawn(PlayerSpawnEvent ev)
{
ev.Player.SetGhostMode(false); //Temp fix for default *True* ghostmode
if (ev.Player != null && ev.Player is Player)
{
- AdminToolbox.AddMissingPlayerVariables(ev.Player);
+ ATFile.AddMissingPlayerVariables(ev.Player);
}
- if (AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserId))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserID, out PlayerSettings pSettings))
{
- PlayerSettings pSettings = AdminToolbox.ATPlayerDict[ev.Player.UserId];
if (pSettings.overwatchMode)
{
pSettings.DeathPos = ev.SpawnPos;
ev.Player.OverwatchMode = true;
}
- else if (ev.Player.TeamRole.Role != Smod2.API.RoleType.TUTORIAL
+ else if (ev.Player.PlayerRole.RoleID != Smod2.API.RoleType.TUTORIAL
&& pSettings.isJailed && !ev.Player.IsInsideJail())
{
JailHandler.SendToJail(ev.Player, pSettings.JailedToTime);
@@ -175,9 +175,11 @@ public void OnSpawn(PlayerSpawnEvent ev)
private int checkNewVersion = 8;
public void OnWaitingForPlayers(WaitingForPlayersEvent ev)
{
- ATFileManager.ConvertOldFilesToNewUserID();
+ Debug($"Entered {System.Reflection.MethodBase.GetCurrentMethod().Name} method");
+ ATFile.RenameOldFilesToNewUserID();
+
AdminToolbox.lockRound = false;
if (AdminToolbox.isStarting)
{
@@ -202,35 +204,35 @@ public void OnWaitingForPlayers(WaitingForPlayersEvent ev)
{
AdminToolbox.intercomLock = Config.GetBoolValue("admintoolbox_intercomlock", false);
}
- //this.plugin.Info(System.Reflection.Assembly.GetExecutingAssembly().Location);
- if (checkNewVersion >= 8)
+ if (checkNewVersion >= 15)
{
checkNewVersion = 0;
if (ATWeb.NewerVersionAvailable())
{
- plugin.Info("\n\n [New Version of AdminToolbox avaiable for download!] [V:" + this.plugin.GetGitReleaseInfo().Version + "]\n " + " Either update via \"AT_AutoUpdate.bat\" or write \"AT DOWNLOAD\"" + "\n\n");
+ plugin.Info($"\n\nNew Version of \"{AdminToolbox.singleton.Details.name}\" avaiable for download! [CURRENT:{AdminToolbox.AT_Version}][NEW:{ATWeb.LatestRelease.Version}]\n" +
+ $"Either update via \"AT_AutoUpdate.bat\" or use the commmand: \"AT DOWNLOAD\"\n\n");
}
}
else
{
checkNewVersion++;
}
- AdminToolbox.warpManager.RefreshWarps();
- AdminToolbox.logManager.ManageDatedATLogs();
+ AdminToolbox.WarpManager.RefreshWarps();
+ AdminToolbox.LogManager.ManageDatedATLogs();
}
public void OnAdminQuery(AdminQueryEvent ev)
{
if (ev.Query != "REQUEST_DATA PLAYER_LIST SILENT")
{
- AdminToolbox.logManager.WriteToLog(new string[] { ev.Admin.Name + " used command: \"" + ev.Query + "\"" }, Managers.LogManager.ServerLogType.RemoteAdminActivity);
+ AdminToolbox.LogManager.WriteToLog(new string[] { ev.Admin.Name + " used command: \"" + ev.Query + "\"" }, Managers.LogManager.ServerLogType.RemoteAdminActivity);
}
}
public void OnLure(PlayerLureEvent ev)
{
int[] TUTallowedDmg = Config.GetIntListValue("admintoolbox_tutorial_dmg_allowed", new int[] { -1 }, false);
- if ((AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserId) && AdminToolbox.ATPlayerDict[ev.Player.UserId].godMode) || (ev.Player.TeamRole.Team == Smod2.API.TeamType.TUTORIAL && !TUTallowedDmg.Contains((int)DamageType.LURE)))
+ if ((AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserID) && AdminToolbox.ATPlayerDict[ev.Player.UserID].godMode) || (ev.Player.PlayerRole.Team == Smod2.API.TeamType.TUTORIAL && !TUTallowedDmg.Contains((int)DamageType.FEMUR_BREAKER)))
{
ev.AllowContain = false;
}
@@ -240,7 +242,7 @@ public void OnContain106(PlayerContain106Event ev)
{
foreach (Player scp106 in ev.SCP106s)
{
- if (AdminToolbox.ATPlayerDict.ContainsKey(scp106.UserId) && (AdminToolbox.ATPlayerDict[scp106.UserId].godMode || AdminToolbox.ATPlayerDict[ev.Player.UserId].dmgOff))
+ if (AdminToolbox.ATPlayerDict.ContainsKey(scp106.UserID) && (AdminToolbox.ATPlayerDict[scp106.UserID].godMode || AdminToolbox.ATPlayerDict[ev.Player.UserID].dmgOff))
{
ev.ActivateContainment = false;
break;
@@ -253,55 +255,56 @@ public void OnPlayerJoin(PlayerJoinEvent ev)
ev.Player.SetGhostMode(false); //Temp fix for default *True* ghostmode
if (!AdminToolbox.isStarting && ev.Player != null && ev.Player is Player player)
{
- AdminToolbox.AddMissingPlayerVariables(player);
- AdminToolbox.atfileManager.PlayerStatsFileManager(player, Managers.ATFileManager.PlayerFile.Read);
+ ATFile.AddMissingPlayerVariables(player);
+ AdminToolbox.FileManager.PlayerStatsFileManager(player, Managers.ATFile.PlayerFile.Read);
if (Config.GetBoolValue("admintoolbox_player_join_info_extended", true, false))
{
- int bancount = AdminToolbox.ATPlayerDict.ContainsKey(player.UserId) ? AdminToolbox.ATPlayerDict[player.UserId].PlayerStats.BanCount : 0;
+ int bancount = AdminToolbox.ATPlayerDict.ContainsKey(player.UserID) ? AdminToolbox.ATPlayerDict[player.UserID].PlayerStats.BanCount : 0;
string str = Environment.NewLine +
- ev.Player.Name + " joined as player (" + player.PlayerId + ")" + Environment.NewLine +
- "From IP: " + player.IpAddress.Replace("::ffff:", string.Empty) + Environment.NewLine +
- "Using UserId: " + player.UserId + Environment.NewLine;
- if (bancount > 0) str += "Player has: \"" + bancount + "\" ban(s) on record" + Environment.NewLine;
+ ev.Player.Name + " joined as player (" + player.PlayerID + ")" + Environment.NewLine +
+ "From IP: " + player.IPAddress.Replace("::ffff:", string.Empty) + Environment.NewLine +
+ "Using UserID: " + player.UserID + Environment.NewLine;
+ if (bancount > 0)
+ str += "Player has: \"" + bancount + "\" ban(s) on record" + Environment.NewLine;
plugin.Info(str);
}
else if (Config.GetBoolValue("admintoolbox_player_join_info", true, false))
{
- plugin.Info(player.Name + " just joined the server!");
+ plugin.Info($"\"{player.Name}\" joined the server!");
}
- if (AdminToolbox.ATPlayerDict.ContainsKey(player.UserId))
+ if (AdminToolbox.ATPlayerDict.ContainsKey(player.UserID))
{
- if (AdminToolbox.ATPlayerDict[player.UserId].overwatchMode)
+ if (AdminToolbox.ATPlayerDict[player.UserID].overwatchMode)
{
ev.Player.OverwatchMode = true;
}
- AdminToolbox.ATPlayerDict[player.UserId].JoinTime = DateTime.Now;
+ AdminToolbox.ATPlayerDict[player.UserID].JoinTime = DateTime.UtcNow;
}
}
}
private static readonly int
JailCheckInterval = Config.GetIntValue("admintoolbox_jailcheck_interval", 5),
- WritePlayerFileInterval = Config.GetIntValue("admintoolbox_writeplayerfile_interval", 180),
- DictCleanupInterval = Config.GetIntValue("admintoolbox_dictcleanup_interval", 300);
+ WritePlayerFileInterval = Config.GetIntValue("admintoolbox_writeplayerfile_interval", 180);
+ //DictCleanupInterval = Config.GetIntValue("admintoolbox_dictcleanup_interval", 300);
- private DateTime oneSecTimer = DateTime.Now,
- fiveSecTimer = DateTime.Now.AddSeconds(5),
- oneMinuteTimer = DateTime.Now.AddSeconds(30),
- threeMinTimer = DateTime.Now.AddMinutes(1)/*,
- fiveMinTimer = DateTime.Now.AddMinutes(2)*/;
+ private DateTime oneSecTimer = DateTime.UtcNow,
+ fiveSecTimer = DateTime.UtcNow.AddSeconds(5),
+ oneMinuteTimer = DateTime.UtcNow.AddSeconds(30),
+ threeMinTimer = DateTime.UtcNow.AddMinutes(1)/*,
+ fiveMinTimer = DateTime.UtcNow.AddMinutes(2)*/;
public void OnUpdate(UpdateEvent ev)
{
- if (oneSecTimer < DateTime.Now)
+ if (oneSecTimer < DateTime.UtcNow)
{
if (AdminToolbox.waitForTeleports.Count > 0)
{
WaitForTeleport[] waitFors = AdminToolbox.waitForTeleports.ToArray();
foreach (WaitForTeleport wft in waitFors)
{
- if (DateTime.Now > wft.DateTime)
+ if (DateTime.UtcNow > wft.DateTime)
{
wft.Player.Teleport(wft.Pos);
wft.Done = true;
@@ -310,9 +313,9 @@ public void OnUpdate(UpdateEvent ev)
AdminToolbox.waitForTeleports.RemoveAll(s => s.Done);
}
- oneSecTimer = DateTime.Now.AddSeconds(1);
+ oneSecTimer = DateTime.UtcNow.AddSeconds(1);
}
- if (fiveSecTimer <= DateTime.Now)
+ if (fiveSecTimer <= DateTime.UtcNow)
{
if (plugin.Server.Round.Duration > 0)
{
@@ -320,23 +323,23 @@ public void OnUpdate(UpdateEvent ev)
}
//if(plugin.scheduledCommands.Count > 0)
//plugin.scheduledCommands.RemoveAll(sch => sch.hasExecuted);
- fiveSecTimer = DateTime.Now.AddSeconds(JailCheckInterval);
+ fiveSecTimer = DateTime.UtcNow.AddSeconds(JailCheckInterval);
}
- if (oneMinuteTimer <= DateTime.Now)
+ if (oneMinuteTimer <= DateTime.UtcNow)
{
AdminToolbox.ATPlayerDict.Cleanup();
- oneMinuteTimer = DateTime.Now.AddMinutes(1);
+ oneMinuteTimer = DateTime.UtcNow.AddMinutes(1);
}
- if (threeMinTimer <= DateTime.Now)
+ if (threeMinTimer <= DateTime.UtcNow)
{
string[] keys = AdminToolbox.ATPlayerDict.Keys.ToArray();
if (keys?.Length > 0)
{
- AdminToolbox.atfileManager.PlayerStatsFileManager(keys, Managers.ATFileManager.PlayerFile.Write);
+ AdminToolbox.FileManager.PlayerStatsFileManager(keys, Managers.ATFile.PlayerFile.Write);
}
- threeMinTimer = DateTime.Now.AddSeconds(WritePlayerFileInterval);
+ threeMinTimer = DateTime.UtcNow.AddSeconds(WritePlayerFileInterval);
}
- //if (fiveMinTimer <= DateTime.Now)
+ //if (fiveMinTimer <= DateTime.UtcNow)
//{
//}
@@ -346,7 +349,10 @@ public void OnStartCountdown(WarheadStartEvent ev)
{
if (Config.GetBoolValue("admintoolbox_custom_nuke_cards", false))
{
- int[] allowedCards = Config.GetIntListValue("admintoolbox_nuke_card_list", new int[] { 6, 9, 11 }, false);
+ int[] allowedCards = Config.GetIntListValue("admintoolbox_nuke_card_list", new int[] {
+ (int)ItemType.KeycardContainmentEngineer,
+ (int)ItemType.KeycardFacilityManager,
+ (int)ItemType.KeycardO5}, false);
ev.Cancel = !allowedCards.Contains((int)ev.Activator.GetCurrentItem().ItemType);
}
}
@@ -354,18 +360,19 @@ public void OnStartCountdown(WarheadStartEvent ev)
public void OnSetServerName(SetServerNameEvent ev)
{
ev.ServerName = ev.ServerName.Replace("$atversion", "AT:" + plugin.Details.version);
- ev.ServerName = Config.GetBoolValue("admintoolbox_tracking", true) ? ev.ServerName += "AT:" + plugin.Details.version + "" : ev.ServerName;
+ if (Config.GetBoolValue("admintoolbox_tracking", true) && !ev.ServerName.Contains("AT:" + plugin.Details.version))
+ ev.ServerName += "AT:" + plugin.Details.version + "";
}
public void OnHandcuffed(PlayerHandcuffedEvent ev)
{
- PlayerSettings playerSetting = Dict.ContainsKey(ev.Player.UserId) ? Dict[ev.Player.UserId] : null;
+ PlayerSettings playerSetting = Dict.ContainsKey(ev.Player.UserID) ? Dict[ev.Player.UserID] : null;
- if (ev.Player.GetGodmode() || (playerSetting?.godMode ?? false))
+ if (ev.Player.GodMode || (playerSetting?.godMode ?? false))
{
ev.Allow = false;
}
- else if (ev.Player.TeamRole.Role == Smod2.API.RoleType.TUTORIAL && !Config.GetBoolValue("admintoolbox_tutorial_canbehandcuffed", false))
+ else if (ev.Player.PlayerRole.RoleID == Smod2.API.RoleType.TUTORIAL && !Config.GetBoolValue("admintoolbox_tutorial_canbehandcuffed", false))
{
ev.Allow = false;
}
@@ -373,36 +380,32 @@ public void OnHandcuffed(PlayerHandcuffedEvent ev)
public void OnBan(BanEvent ev)
{
- string[] banWebhookUrls = Config.GetListValue("admintoolbox_ban_webhooks", new string[0], false);
+ if (Config.GetBoolValue("admintoolbox_ban_console_info", true))
+ Info($"\nPlayer \"{ev.Player.Name}\" banned.\n" +
+ $"ID: {ev.Player.UserID}" +
+ $"Duration: {ev.Duration / 60} minutes\n" +
+ $"Reason: {(string.IsNullOrEmpty(ev.Reason) ? "Unspecified" : ev.Reason)}\n" +
+ $"Issuer: {(string.IsNullOrEmpty(ev.Issuer) ? "Unspecified" : ev.Issuer)}\n");
+
+
+ string[] banWebhookUrls = Config.GetListValue("admintoolbox_ban_webhooks", new string[0]);
if (banWebhookUrls.Length > 0 && (ev.Duration > 0 || Config.GetBoolValue("admintoolbox_ban_webhook_onkick", false)))
- {
- DiscordWebhook webH;
- List listOfFields = new List();
-
- listOfFields.AddField("Playername: ", ev.Player.Name);
- listOfFields.AddField("Duration: ", (ev.Duration / 60).ToString("0.0", CultureInfo.InvariantCulture) + " hours");
- if (!string.IsNullOrEmpty(ev.Reason))
- listOfFields.AddField("Reason: ", ev.Reason);
- if (Config.GetBoolValue("admintoolbox_ban_webhook_include_admin", false))
- listOfFields.AddField("Issued By: ", ev.Issuer ?? "Server");
-
- webH = new DiscordWebhook { embeds = new EmbedData[] { new EmbedData { author = new Author { name = "User Banned: " }, title = "", fields = listOfFields.ToArray() } } };
-
+ {
foreach (string url in banWebhookUrls)
if (!string.IsNullOrEmpty(url))
- plugin.Debug(ATWeb.SendWebhook(webH, url));
- plugin.Info("Ban webhooks posted!");
+ plugin.Debug(ATWeb.SendWebhook(Utility.BuildBanWebhook(ev.Player, (int)ev.Duration, ev.Reason, ev.Issuer), url));
+ Debug($"Player \"{ev.Player.Name}\" banned, Webhook posted.");
}
if (ev.Player != null && ev.Player is Player)
{
- AdminToolbox.AddMissingPlayerVariables(ev.Player);
+ ATFile.AddMissingPlayerVariables(ev.Player);
}
- if (AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserId) && ev.Duration > 1)
+ if (AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserID) && ev.Duration > 1)
{
- AdminToolbox.ATPlayerDict[ev.Player.UserId].PlayerStats.BanCount++;
- AdminToolbox.atfileManager.PlayerStatsFileManager(ev.Player.UserId);
+ AdminToolbox.ATPlayerDict[ev.Player.UserID].PlayerStats.BanCount++;
+ AdminToolbox.FileManager.PlayerStatsFileManager(ev.Player.UserID);
}
}
@@ -414,31 +417,31 @@ public void OnTeamRespawn(TeamRespawnEvent ev)
public void OnThrowGrenade(PlayerThrowGrenadeEvent ev)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserID, out PlayerSettings ps))
{
if (ps.isJailed || ps.lockDown)
ev.Allow = false;
- else if (ps.grenadeMode || ps.InfiniteItem == Smod2.API.ItemType.FRAG_GRENADE || ps.InfiniteItem == Smod2.API.ItemType.FLASHBANG)
- ev.Player.GiveItem((ev.GrenadeType == GrenadeType.FRAG_GRENADE) ? Smod2.API.ItemType.FRAG_GRENADE : Smod2.API.ItemType.FLASHBANG);
+ else if (ps.grenadeMode || ps.InfiniteItem == Smod2.API.ItemType.GRENADE_HE || ps.InfiniteItem == Smod2.API.ItemType.GRENADE_FLASH)
+ ev.Player.GiveItem((Smod2.API.ItemType)(int)ev.GrenadeType);
}
}
public void OnPlayerDropItem(PlayerDropItemEvent ev)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserId, out PlayerSettings ps))
+ if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserID, out PlayerSettings ps))
{
if (ps.isJailed || ps.lockDown)
ev.Allow = false;
- else if (ps.InfiniteItem != Smod2.API.ItemType.NULL && ev.Item.ItemType == ps.InfiniteItem)
+ else if (ps.InfiniteItem != Smod2.API.ItemType.NONE && ev.Item.ItemType == ps.InfiniteItem)
ev.Player.GiveItem(ps.InfiniteItem);
- else if (ps.grenadeMode && ev.Item.ItemType == Smod2.API.ItemType.FRAG_GRENADE)
- ev.Player.GiveItem(Smod2.API.ItemType.FRAG_GRENADE);
+ else if (ps.grenadeMode && ev.Item.ItemType == Smod2.API.ItemType.GRENADE_HE)
+ ev.Player.GiveItem(Smod2.API.ItemType.GRENADE_HE);
}
}
public void OnReload(PlayerReloadEvent ev)
{
- if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserId, out PlayerSettings ps) && ps.InfiniteItem != Smod2.API.ItemType.NULL)
+ if (AdminToolbox.ATPlayerDict.TryGetValue(ev.Player.UserID, out PlayerSettings ps) && ps.InfiniteItem != Smod2.API.ItemType.NONE)
if (ps.InfiniteItem.ToString().Contains("DROPPED"))
foreach (AmmoType ammo in Enum.GetValues(typeof(AmmoType)))
if (ammo.ToString() == ps.InfiniteItem.ToString())
@@ -448,16 +451,16 @@ public void OnReload(PlayerReloadEvent ev)
}
}
}
-#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
- public class LateEscapeEventCheck : IEventHandlerCheckEscape
+
+
+ internal class LateEscapeEventCheck : IEventHandlerCheckEscape
{
public void OnCheckEscape(PlayerCheckEscapeEvent ev)
{
- if (ev.AllowEscape && AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserId))
+ if (ev.AllowEscape && AdminToolbox.ATPlayerDict.ContainsKey(ev.Player.UserID))
{
- AdminToolbox.ATPlayerDict[ev.Player.UserId].PlayerStats.EscapeCount++;
+ AdminToolbox.ATPlayerDict[ev.Player.UserID].PlayerStats.EscapeCount++;
}
}
}
-#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
}
diff --git a/AdminToolbox/AdminToolbox/Events/PlayerDamageEvent.cs b/AdminToolbox/AdminToolbox/Events/PlayerDamageEvent.cs
index dbe679a..7972740 100644
--- a/AdminToolbox/AdminToolbox/Events/PlayerDamageEvent.cs
+++ b/AdminToolbox/AdminToolbox/Events/PlayerDamageEvent.cs
@@ -11,7 +11,7 @@ namespace AdminToolbox
using API;
using API.Extentions;
- internal class DamageDetect : IEventHandlerPlayerHurt
+ internal class PlayerDamageEvent : IEventHandlerPlayerHurt
{
private IConfigFile Config => ConfigManager.Manager.Config;
@@ -19,7 +19,7 @@ internal class DamageDetect : IEventHandlerPlayerHurt
private Dictionary Dict => AdminToolbox.ATPlayerDict;
- public DamageDetect(AdminToolbox plugin) => this.plugin = plugin;
+ public PlayerDamageEvent(AdminToolbox plugin) => this.plugin = plugin;
private int[] CalculateTutorialDamage()
{
@@ -56,10 +56,10 @@ private int[] CalculateTutorialDamage()
public void OnPlayerHurt(PlayerHurtEvent ev)
{
- AdminToolbox.AddMissingPlayerVariables(new Player[] { ev.Attacker, ev.Player });
+ Managers.ATFile.AddMissingPlayerVariables(new Player[] { ev.Attacker, ev.Player });
- Dict.TryGetValue(ev.Player.UserId, out PlayerSettings playerSetting);
- Dict.TryGetValue(ev.Attacker.UserId, out PlayerSettings attackerSetting);
+ Dict.TryGetValue(ev.Player.UserID, out PlayerSettings playerSetting);
+ Dict.TryGetValue(ev.Attacker.UserID, out PlayerSettings attackerSetting);
float originalDamage = ev.Damage;
DamageType originalType = ev.DamageType;
@@ -71,10 +71,12 @@ public void OnPlayerHurt(PlayerHurtEvent ev)
ev.Damage = 0f;
else if ((attackerSetting?.isJailed ?? false) || (attackerSetting?.dmgOff ?? false))
ev.Damage = 0f;
+ //else if (ev.DamageType == DamageType.FLYING_DETECTION && Config.GetBoolValue("admintoolbox_antifly_disable", false))
+ //ev.Damage = 0f;
int[] allowedTutDmg = new int[] { -1 };
- if (ev.Player.TeamRole.Role == Smod2.API.RoleType.TUTORIAL)
+ if (ev.Player.PlayerRole.RoleID == Smod2.API.RoleType.TUTORIAL)
allowedTutDmg = CalculateTutorialDamage();
int[] DebugDmg = Config.GetIntListValue("admintoolbox_debug_damagetypes", Utility.HumanDamageTypes, false);
@@ -85,8 +87,8 @@ public void OnPlayerHurt(PlayerHurtEvent ev)
roleDamages[0] = _roleDamagesDefault;
- if (ev.DamageType != DamageType.FRAG && (attackerSetting?.instantKill ?? false))
- ev.Damage = ev.Player.GetHealth() + 1;
+ if (ev.DamageType != DamageType.EXPLOSION && (attackerSetting?.instantKill ?? false))
+ ev.Damage = ev.Player.Health + ev.Player.ArtificialHealth + 1;
if (ev.Player.IsHandcuffed() && Utility.HumanDamageTypes.Contains((int)ev.DamageType) && Config.GetBoolValue("admintoolbox_nokill_captured", false))
{
@@ -98,7 +100,7 @@ public void OnPlayerHurt(PlayerHurtEvent ev)
}
if (AdminToolbox.isRoundFinished && !Config.GetBoolValue("admintoolbox_roledamageblock_onroundend", true)) goto RoundEnd;
- if (roleDamages.Length > 0 && ev.Attacker.PlayerId != ev.Player.PlayerId)
+ if (roleDamages.Length > 0 && ev.Attacker.PlayerID != ev.Player.PlayerID)
{
bool foundPlayer = false;
foreach (string item in roleDamages)
@@ -113,12 +115,12 @@ public void OnPlayerHurt(PlayerHurtEvent ev)
{
if (int.TryParse(item2, out int victimIntRole) && Utility.TryParseRole(victimIntRole, out Smod2.API.RoleType victimRole))
{
- if (attackerRole == ev.Attacker.TeamRole.Role && victimRole == ev.Player.TeamRole.Role)
+ if (attackerRole == ev.Attacker.PlayerRole.RoleID && victimRole == ev.Player.PlayerRole.RoleID)
{
if (attackerSetting?.instantKill ?? false) continue;
ev.Damage = 0f;
- ev.DamageType = DamageType.NONE;
- plugin.Debug(ev.Attacker.TeamRole.Name + " " + ev.Attacker.Name + "was blocked from attacking " + ev.Player.TeamRole.Name + " " + ev.Player + " with " + ev.DamageType);
+ //ev.DamageType = DamageType.NONE;
+ plugin.Debug(ev.Attacker.PlayerRole.Name + " " + ev.Attacker.Name + "was blocked from attacking " + ev.Player.PlayerRole.Name + " " + ev.Player + " with " + ev.DamageType);
foundPlayer = true;
break;
}
@@ -146,22 +148,22 @@ public void OnPlayerHurt(PlayerHurtEvent ev)
if (!(attackerSetting?.instantKill ?? false))
ev.Damage = originalDamage * enddamageMultiplier;
}
- switch (ev.Player.TeamRole.Role)
+ switch (ev.Player.PlayerRole.RoleID)
{
case Smod2.API.RoleType.TUTORIAL:
if (allowedTutDmg.Contains((int)ev.DamageType) || allowedTutDmg.Contains(-2))
goto default;
if (DebugDmg.Contains((int)ev.DamageType) && Config.GetBoolValue("admintoolbox_debug_tutorial", false, false))
- plugin.Info(ev.Player.TeamRole.Name + " " + ev.Player.Name + " not allowed damagetype: " + ev.DamageType);
+ plugin.Info(ev.Player.PlayerRole.Name + " " + ev.Player.Name + " not allowed damagetype: " + ev.DamageType);
if ((attackerSetting?.instantKill ?? false) && Config.GetBoolValue("admintoolbox_instantkill_affects_tutorials", true))
goto default;
- ev.DamageType = DamageType.NONE;
+ //ev.DamageType = DamageType.NONE;
ev.Damage = 0f;
break;
default:
if (AdminToolbox.isRoundFinished) break;
- ev.Damage = (ev.DamageType == DamageType.DECONT) ? originalDamage * Config.GetFloatValue("admintoolbox_decontamination_damagemultiplier", 1f, true) : ev.Damage;
+ ev.Damage = (ev.DamageType == DamageType.DECONTAMINATION) ? originalDamage * Config.GetFloatValue("admintoolbox_decontamination_damagemultiplier", 1f, true) : ev.Damage;
if ((ev.Attacker.Name == "Server" && !Config.GetBoolValue("admintoolbox_debug_server", false, false)) || (ev.Attacker.Name == "Spectator" &&
!Config.GetBoolValue("admintoolbox_debug_spectator", false, false))) return;
if (Utility.IsTeam(ev.Player, ev.Attacker))
@@ -170,78 +172,81 @@ public void OnPlayerHurt(PlayerHurtEvent ev)
{
ev.Damage = (ev.Damage >= 1) ? Config.GetFloatValue("admintoolbox_friendlyfire_damagemultiplier", 1f) * originalDamage : ev.Damage;
if (DebugDmg.Contains((int)ev.DamageType) && !AdminToolbox.isRoundFinished)
- plugin.Info(ev.Attacker.TeamRole.Name + " " + ev.Attacker.Name + " attacked fellow " + ev.Player.TeamRole.Name + " " + ev.Player.Name + /*" for " + damage +^*/ " with " + ev.DamageType);
+ plugin.Info(ev.Attacker.PlayerRole.Name + " " + ev.Attacker.Name + " attacked fellow " + ev.Player.PlayerRole.Name + " " + ev.Player.Name + /*" for " + damage +^*/ " with " + ev.DamageType);
}
}
else if (Config.GetBoolValue("admintoolbox_debug_player_damage", false, false))
{
if (DebugDmg.Contains((int)ev.DamageType) && !AdminToolbox.isRoundFinished)
- plugin.Info(ev.Attacker.TeamRole.Name + " " + ev.Attacker.Name + " attacked " + ev.Player.TeamRole.Name + " " + ev.Player.Name + /*" for " + ev.Damage + " damage" +*/ " with: " + ev.DamageType);
+ plugin.Info(ev.Attacker.PlayerRole.Name + " " + ev.Attacker.Name + " attacked " + ev.Player.PlayerRole.Name + " " + ev.Player.Name + /*" for " + ev.Damage + " damage" +*/ " with: " + ev.DamageType);
}
break;
}
- if (ev.Damage >= ev.Player.GetHealth() && playerSetting != null)
+ if (ev.Damage >= (ev.Player.Health + ev.Player.ArtificialHealth) && playerSetting != null)
{
playerSetting.DeathPos = ev.Player.GetPosition();
if (playerSetting.grenadeMode)
- ev.Player.ThrowGrenade(GrenadeType.FRAG_GRENADE, true, Vector.Zero, false, ev.Player.GetPosition(), true, 0f, true);
+ ev.Player.ThrowGrenade(GrenadeType.GRENADE_HE, Vector.Zero, slowThrow: true);
}
- AdminToolbox.logManager.WriteToLog(ev.Attacker.TeamRole.Name + " " + ev.Attacker.Name + " attacked " + ev.Player.TeamRole.Name + " " + ev.Player.Name + " for " + ev.Damage + " damage" + " with: " + ev.DamageType, Managers.LogManager.ServerLogType.PlayerDamage);
+ AdminToolbox.LogManager.WriteToLog(ev.Attacker.PlayerRole.Name + " " + ev.Attacker.Name + " attacked " + ev.Player.PlayerRole.Name + " " + ev.Player.Name + " for " + ev.Damage + " damage" + " with: " + ev.DamageType, Managers.LogManager.ServerLogType.PlayerDamage);
}
}
- public class DieDetect : IEventHandlerPlayerDie
+ public class PlayerDieEvent : IEventHandlerPlayerDie
{
private readonly Plugin plugin;
private IConfigFile Config => ConfigManager.Manager.Config;
- private Server Server => PluginManager.Manager.Server;
private Dictionary Dict => AdminToolbox.ATPlayerDict;
- public DieDetect(Plugin plugin) => this.plugin = plugin;
+ public PlayerDieEvent(Plugin plugin) => this.plugin = plugin;
public void OnPlayerDie(PlayerDeathEvent ev)
{
- AdminToolbox.AddMissingPlayerVariables(new Player[] { ev.Player, ev.Killer });
- Dict.TryGetValue(ev.Player.UserId, out PlayerSettings playerSetting);
- Dict.TryGetValue(ev.Killer.UserId, out PlayerSettings killerSetting);
+ Managers.ATFile.AddMissingPlayerVariables(new Player[] { ev.Player, ev.Killer });
+ Dict.TryGetValue(ev.Player.UserID, out PlayerSettings playerSetting);
+ Dict.TryGetValue(ev.Killer.UserID, out PlayerSettings killerSetting);
- switch ((int)ev.Player.TeamRole.Role)
+ switch ((int)ev.Player.PlayerRole.RoleID)
{
case 3:
- if (ev.DamageTypeVar == DamageType.LURE || ev.DamageTypeVar == DamageType.CONTAIN)
+ if (ev.DamageTypeVar == DamageType.RECONTAINED)
+ {
ev.SpawnRagdoll = false;
+ //ev.DamageTypeVar = DamageType.RAGDOLLLESS;
+ }
goto default;
default:
if (AdminToolbox.isRoundFinished)
break;
- if (playerSetting != null && ev.Killer?.PlayerId != ev.Player?.PlayerId)
+ if (playerSetting != null && ev.Killer?.PlayerID != ev.Player?.PlayerID)
playerSetting.PlayerStats.Deaths++;
- if (ev.Player?.PlayerId == ev.Killer?.PlayerId && !Config.GetBoolValue("admintoolbox_debug_scp_and_self_killed", false, false))
+ if (ev.Player?.PlayerID == ev.Killer?.PlayerID && !Config.GetBoolValue("admintoolbox_debug_scp_and_self_killed", false, false))
return;
if (Utility.IsTeam(ev.Player, ev.Killer))
{
- string keyWord = (ev.DamageTypeVar == DamageType.FRAG) ? "granaded" : "killed";
- if (killerSetting != null && ev.Killer.PlayerId != ev.Player.PlayerId) killerSetting.PlayerStats.TeamKills++;
+ string keyWord = (ev.DamageTypeVar == DamageType.EXPLOSION) ? "granaded" : "killed";
+ if (killerSetting != null && ev.Killer.PlayerID != ev.Player.PlayerID)
+ killerSetting.PlayerStats.TeamKills++;
if (Config.GetBoolValue("admintoolbox_debug_friendly_kill", true, false))
if (AdminToolbox.isColored)
plugin.Info(ev.Killer.ToColoredMultiAdminTeam() + " @#fg=Yellow;" + ev.Killer.Name + "@#fg=DarkRed; " + keyWord + " fellow @#fg=Default;" + ev.Player.ToColoredMultiAdminTeam() + "@#fg=Yellow; " + ev.Player.Name + "@#fg=Default;");
else
- plugin.Info(ev.Killer.TeamRole.Name + " " + ev.Killer.Name + " " + keyWord + " fellow " + ev.Player.TeamRole.Name + " " + ev.Player.Name);
- AdminToolbox.logManager.WriteToLog(ev.Killer.TeamRole.Name + " " + ev.Killer.Name + " " + keyWord + " fellow " + ev.Player.TeamRole.Name + " " + ev.Player.Name, Managers.LogManager.ServerLogType.TeamKill);
+ plugin.Info(ev.Killer.PlayerRole.Name + " " + ev.Killer.Name + " " + keyWord + " fellow " + ev.Player.PlayerRole.Name + " " + ev.Player.Name);
+ AdminToolbox.LogManager.WriteToLog(ev.Killer.PlayerRole.Name + " " + ev.Killer.Name + " " + keyWord + " fellow " + ev.Player.PlayerRole.Name + " " + ev.Player.Name, Managers.LogManager.ServerLogType.TeamKill);
}
else
{
if (Config.GetBoolValue("admintoolbox_debug_player_kill", false, false))
plugin.Info(ev.Killer.Name + " killed: " + ev.Player.Name);
- if (killerSetting != null && ev.Killer.PlayerId != ev.Player.PlayerId)
+ if (killerSetting != null && ev.Killer.PlayerID != ev.Player.PlayerID)
killerSetting.PlayerStats.Kills++;
- AdminToolbox.logManager.WriteToLog(ev.Killer.TeamRole.Name + " " + ev.Killer.Name + " killed " + ev.Player.TeamRole.Name + " " + ev.Player.Name, Managers.LogManager.ServerLogType.KillLog);
+ AdminToolbox.LogManager.WriteToLog(ev.Killer.PlayerRole.Name + " " + ev.Killer.Name + " killed " + ev.Player.PlayerRole.Name + " " + ev.Player.Name, Managers.LogManager.ServerLogType.KillLog);
}
break;
}
- if (ev.Player.PlayerId == ev.Killer.PlayerId && playerSetting != null)
+ if (ev.Player.PlayerID == ev.Killer.PlayerID && playerSetting != null)
playerSetting.PlayerStats.SuicideCount++;
}
}
diff --git a/AdminToolbox/AdminToolbox/Events/RoundEventHandler.cs b/AdminToolbox/AdminToolbox/Events/RoundEventHandler.cs
index 9ae0fca..22ffcdc 100644
--- a/AdminToolbox/AdminToolbox/Events/RoundEventHandler.cs
+++ b/AdminToolbox/AdminToolbox/Events/RoundEventHandler.cs
@@ -30,27 +30,27 @@ public void OnRoundStart(RoundStartEvent ev)
AdminToolbox.isRoundFinished = false;
if (Config.GetBoolValue("admintoolbox_round_info", true, false))
{
- plugin.Info("Round: " + ++AdminToolbox.RoundCount + " started.");
+ plugin.Info("Round: " + ++AdminToolbox.RoundCount + " start");
plugin.Info("Players this round: " + ev.Server.NumPlayers);
}
- AdminToolbox.AddMissingPlayerVariables();
- AdminToolbox.atfileManager.PlayerStatsFileManager(Managers.ATFileManager.PlayerFile.Write);
- AdminToolbox.logManager.SetLogStartTime();
- AdminToolbox.warpManager.RefreshWarps();
+ Managers.ATFile.AddMissingPlayerVariables();
+ AdminToolbox.FileManager.PlayerStatsFileManager(Managers.ATFile.PlayerFile.Write);
+ AdminToolbox.LogManager.SetLogStartTime();
+ AdminToolbox.WarpManager.RefreshWarps();
AdminToolbox.roundStatsRecorded = false;
- if (intercomReady != string.Empty)
+ if (!string.IsNullOrEmpty(intercomReady))
{
- ev.Server.Map.SetIntercomContent(IntercomStatus.Ready, intercomReady);
+ ev.Server.Map.SetIntercomContent(IntercomStatus.READY, intercomReady);
}
- if (intercomRestart != string.Empty)
+ if (!string.IsNullOrEmpty(intercomRestart))
{
- ev.Server.Map.SetIntercomContent(IntercomStatus.Restarting, intercomRestart);
+ ev.Server.Map.SetIntercomContent(IntercomStatus.RESTARTING, intercomRestart);
}
- if (intercomTransmit != string.Empty)
+ if (!string.IsNullOrEmpty(intercomTransmit))
{
- ev.Server.Map.SetIntercomContent(IntercomStatus.Transmitting, intercomTransmit);
+ ev.Server.Map.SetIntercomContent(IntercomStatus.TRANSMITTING, intercomTransmit);
}
}
@@ -59,7 +59,7 @@ public void OnCheckRoundEnd(CheckRoundEndEvent ev)
{
if (AdminToolbox.lockRound)
{
- ev.Status = ROUND_END_STATUS.ON_GOING;
+ ev.Status = RoundEndStatus.ON_GOING;
}
}
@@ -80,7 +80,7 @@ public void OnRoundEnd(RoundEndEvent ev)
plugin.Info("Round lasted for: " + minutes + " min, " + (duration - (minutes * 60)) + " sec");
}
- AdminToolbox.AddMissingPlayerVariables();
+ Managers.ATFile.AddMissingPlayerVariables();
string[] keys = AdminToolbox.ATPlayerDict.Keys.ToArray();
if (keys.Length > 0)
@@ -102,7 +102,7 @@ public void OnRoundRestart(RoundRestartEvent ev)
AdminToolbox.lockRound = false;
if (AdminToolbox.ATPlayerDict.Count > 0)
{
- AdminToolbox.ATPlayerDict.Keys.ResetPlayerBools();
+ AdminToolbox.ATPlayerDict.ResetPlayerBools();
}
string[] keys = AdminToolbox.ATPlayerDict.Keys.ToArray();
@@ -112,12 +112,12 @@ public void OnRoundRestart(RoundRestartEvent ev)
if (AdminToolbox.ATPlayerDict.ContainsKey(key))
{
PlayerSettings ps = AdminToolbox.ATPlayerDict[key];
- ps.PlayerStats.MinutesPlayed += DateTime.Now.Subtract(ps.JoinTime).TotalSeconds;
+ ps.PlayerStats.MinutesPlayed += DateTime.UtcNow.Subtract(ps.JoinTime).TotalSeconds;
AdminToolbox.ATPlayerDict[key] = ps;
}
}
- AdminToolbox.atfileManager.PlayerStatsFileManager(AdminToolbox.ATPlayerDict.Keys.ToArray(), Managers.ATFileManager.PlayerFile.Write);
+ AdminToolbox.FileManager.PlayerStatsFileManager(AdminToolbox.ATPlayerDict.Keys.ToArray(), Managers.ATFile.PlayerFile.Write);
}
}
}
diff --git a/AdminToolbox/AdminToolbox/Managers/ATFile.cs b/AdminToolbox/AdminToolbox/Managers/ATFile.cs
new file mode 100644
index 0000000..778a521
--- /dev/null
+++ b/AdminToolbox/AdminToolbox/Managers/ATFile.cs
@@ -0,0 +1,497 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using Smod2;
+using Smod2.API;
+using System.Text.RegularExpressions;
+
+namespace AdminToolbox.Managers
+{
+ using API;
+
+ internal enum Folder
+ {
+ AppData,
+ ATRoot,
+ PlayerFiles,
+ Logs,
+ Warps
+ }
+
+ ///
+ /// Contains all -related functionality
+ ///
+ ///
+ public class ATFile
+ {
+ private static IConfigFile Config => ConfigManager.Manager.Config;
+ private static Server Server => PluginManager.Manager.Server;
+ private static int Port => PluginManager.Manager.Server.Port;
+ private static AdminToolbox Plugin => AdminToolbox.singleton;
+ private static void Debug(string str) => Plugin.Debug($"[{typeof(ATFile).Name}]: " + str);
+ private static void Info(string str) => Plugin.Info($"[{typeof(ATFile).Name}]: " + str);
+
+ internal const char SplitChar = ';';
+
+ internal bool ProcessingCollection = false;
+
+ ///
+ /// for
+ ///
+ public enum PlayerFile
+ {
+ Read = 0,
+ Write = 1
+ }
+
+
+ private static string GetFolderPath()
+ {
+ string cnfgpath = Config.GetStringValue("admintoolbox_folder_path", string.Empty);
+ if (!string.IsNullOrEmpty(cnfgpath))
+ {
+ if (!cnfgpath.EndsWith(Path.DirectorySeparatorChar.ToString()))
+ cnfgpath += Path.DirectorySeparatorChar;
+ cnfgpath += "AdminToolbox" + Path.DirectorySeparatorChar;
+ }
+ else
+ {
+ cnfgpath = FileManager.GetAppFolder(addSeparator: true) + "AdminToolbox" + Path.DirectorySeparatorChar;
+ }
+ if (!Directory.Exists(cnfgpath))
+ Directory.CreateDirectory(cnfgpath);
+ return cnfgpath;
+ }
+
+ internal static string GetFolderPath(Folder folder = Folder.ATRoot)
+ {
+
+ string ret = GetFolderPath();
+ switch (folder)
+ {
+ case Folder.PlayerFiles:
+ ret += "PlayerStats" + Path.DirectorySeparatorChar;
+ if (!Directory.Exists(ret))
+ Directory.CreateDirectory(ret);
+ if (Config.GetBoolValue("admintoolbox_stats_unified", true))
+ ret += "Global" + Path.DirectorySeparatorChar;
+ else
+ ret += Port + Path.DirectorySeparatorChar;
+ break;
+
+ case Folder.Logs:
+ ret += "ServerLogs" + Path.DirectorySeparatorChar;
+ break;
+
+ case Folder.Warps:
+ ret += "WarpPoints" + Path.DirectorySeparatorChar;
+ break;
+
+ case Folder.AppData:
+ return FileManager.GetAppFolder(addSeparator: true);
+
+ case Folder.ATRoot:
+ default:
+ break;
+ }
+ if (!Directory.Exists(ret))
+ Directory.CreateDirectory(ret);
+ return ret;
+ }
+
+ [Smod2.Piping.PipeProperty(true, false)]
+ public static string MainPath =>
+ GetFolderPath();
+
+ [Smod2.Piping.PipeProperty(true, false)]
+ internal static string PlayerStatsPath =>
+ GetFolderPath(Folder.PlayerFiles);
+
+ [Smod2.Piping.PipeProperty(true, false)]
+ internal static string LogPath =>
+ GetFolderPath(Folder.Logs);
+
+ ///
+ /// Read/Writes stats to/from
+ ///
+ public void PlayerStatsFileManager(PlayerFile FileOperation = PlayerFile.Read) => PlayerStatsFileManager(new string[] { }, FileOperation);
+
+ ///
+ /// Read/Writes the 's stats to/from
+ ///
+ public void PlayerStatsFileManager(string UserID, PlayerFile FileOperation = PlayerFile.Write) => PlayerStatsFileManager(new string[] { UserID }, FileOperation);
+
+ ///
+ /// Read/Writes stats to/from
+ ///
+ public void PlayerStatsFileManager(Player player, PlayerFile FileOperation = PlayerFile.Write) => PlayerStatsFileManager(new string[] { player.UserID }, FileOperation);
+
+ ///
+ /// Read/Writes stats to/from for each in the
+ ///
+ public void PlayerStatsFileManager(List playerList, PlayerFile FileOperation = PlayerFile.Read)
+ {
+ if (playerList != null && playerList.Count > 0)
+ PlayerStatsFileManager(playerList.Select(p => p.UserID).ToArray(), FileOperation);
+ else
+ PlayerStatsFileManager(FileOperation);
+ }
+
+ ///
+ /// Read/Writes stats to/from for each UserID in the
+ ///
+ public void PlayerStatsFileManager(List UserIDList, PlayerFile FileOperation = PlayerFile.Read)
+ {
+ if (UserIDList != null && UserIDList.Count > 0)
+ PlayerStatsFileManager(UserIDList.ToArray(), FileOperation);
+ else
+ PlayerStatsFileManager(new string[0], FileOperation);
+ }
+
+ ///
+ /// Read/Writes stats to/from for each UserID in the
+ ///
+ public void PlayerStatsFileManager(string[] UserIDArray, PlayerFile FileOperation = PlayerFile.Read)
+ {
+ if (!Config.GetBoolValue("admintoolbox_playerfiles", true))
+ return;
+ if (Directory.Exists(MainPath))
+ {
+ if (!Directory.Exists(MainPath))
+ Directory.CreateDirectory(MainPath);
+ if (!Directory.Exists(PlayerStatsPath))
+ Directory.CreateDirectory(PlayerStatsPath);
+
+ ProcessingCollection = true;
+
+ if (UserIDArray == null || UserIDArray.Length < 1)
+ UserIDArray = AdminToolbox.ATPlayerDict.Keys.ToArray();
+ foreach (string id in UserIDArray)
+ {
+ if (string.IsNullOrEmpty(id))
+ return;
+ if (!AdminToolbox.ATPlayerDict.ContainsKey(id))
+ {
+ AddMissingPlayerVariables(Server.GetPlayers(id));
+ continue;
+ }
+ switch (FileOperation)
+ {
+ case PlayerFile.Write:
+ WriteToFile(id);
+ continue;
+ case PlayerFile.Read:
+ default:
+ ReadFromFile(id);
+ continue;
+ }
+ }
+
+ ProcessingCollection = false;
+ }
+ }
+
+ #region NewFilesStuff -The new JSON stuff
+#pragma warning disable IDE0051 // Remove unused private members
+ private void NewWriteToFile(string UserID)
+ {
+ if (!AdminToolbox.ATPlayerDict.ContainsKey(UserID))
+ return;
+ string playerFilePath = PlayerStatsPath + UserID + ".txt";
+ if (!File.Exists(playerFilePath))
+ File.Create(playerFilePath).Dispose();
+
+ if (File.ReadAllLines(playerFilePath).Length <= 2)
+ ConvertOldFilesToJSON(playerFilePath);
+
+ SerializablePlayerClass pl = new SerializablePlayerClass(AdminToolbox.ATPlayerDict[UserID]);
+
+ if (string.IsNullOrEmpty(pl.PlayerInfo.FirstJoin))
+ pl.PlayerInfo.FirstJoin = DateTime.UtcNow.AddMinutes(-pl.PlayerStats.MinutesPlayed).ToString(CultureInfo.InvariantCulture);
+
+ using (StreamWriter sw = new StreamWriter(playerFilePath, false))
+ {
+ sw.WriteLine(Utf8Json.JsonSerializer.PrettyPrint(Utf8Json.JsonSerializer.Serialize(pl)));
+ }
+ }
+ private void NewReadFromFile(string UserID)
+ {
+ if (!AdminToolbox.ATPlayerDict.ContainsKey(UserID))
+ return;
+ string playerFilePath = PlayerStatsPath + UserID + ".txt";
+ if (!File.Exists(playerFilePath))
+ WriteToFile(UserID);
+
+ if (File.ReadAllLines(playerFilePath).Length <= 2)
+ ConvertOldFilesToJSON(playerFilePath);
+
+ string rawJSON = File.ReadAllText(playerFilePath);
+ SerializablePlayerClass pl = Utf8Json.JsonSerializer.Deserialize(rawJSON);
+
+ PlayerSettings playersetting = AdminToolbox.ATPlayerDict[UserID];
+
+ if (string.IsNullOrEmpty(pl.PlayerInfo.FirstJoin))
+ playersetting.PlayerInfo.FirstJoin = DateTime.UtcNow.AddMinutes(-pl.PlayerStats.MinutesPlayed).ToString(CultureInfo.InvariantCulture);
+ playersetting.PlayerStats = pl.PlayerStats;
+ }
+#pragma warning restore IDE0051 // Remove unused private members
+ #endregion
+
+ private void WriteToFile(string UserID)
+ {
+ if (!AdminToolbox.ATPlayerDict.ContainsKey(UserID))
+ {
+ if (PluginManager.Manager.Server.GetPlayers(UserID).Count < 1)
+ return;
+ AddMissingPlayerVariables(PluginManager.Manager.Server.GetPlayers(UserID));
+ }
+ if (!AdminToolbox.ATPlayerDict.ContainsKey(UserID) || UserID == "----------------------------------------")
+ return;
+ string playerFilePath = AdminToolbox.ATPlayerDict.ContainsKey(UserID) ? PlayerStatsPath + Path.DirectorySeparatorChar + UserID + ".txt" : PlayerStatsPath + Path.DirectorySeparatorChar + "server" + ".txt";
+ if (!File.Exists(playerFilePath))
+ File.Create(playerFilePath).Dispose();
+ Debug("Writing: " + playerFilePath);
+
+ string Kills = ((AdminToolbox.ATPlayerDict.ContainsKey(UserID) && AdminToolbox.ATPlayerDict[UserID].PlayerStats.Kills > 0) ? AdminToolbox.ATPlayerDict[UserID].PlayerStats.Kills : 0).ToString(CultureInfo.InvariantCulture);
+ string TeamKills = ((AdminToolbox.ATPlayerDict.ContainsKey(UserID) && AdminToolbox.ATPlayerDict[UserID].PlayerStats.TeamKills > 0) ? AdminToolbox.ATPlayerDict[UserID].PlayerStats.TeamKills : 0).ToString(CultureInfo.InvariantCulture);
+ string Deaths = ((AdminToolbox.ATPlayerDict.ContainsKey(UserID) && AdminToolbox.ATPlayerDict[UserID].PlayerStats.Deaths > 0) ? AdminToolbox.ATPlayerDict[UserID].PlayerStats.Deaths : 0).ToString(CultureInfo.InvariantCulture);
+ string minutesPlayed = ((AdminToolbox.ATPlayerDict.ContainsKey(UserID) && AdminToolbox.ATPlayerDict[UserID].PlayerStats.MinutesPlayed > 0) ? DateTime.UtcNow.Subtract(AdminToolbox.ATPlayerDict[UserID].JoinTime).TotalMinutes + AdminToolbox.ATPlayerDict[UserID].PlayerStats.MinutesPlayed : 0).ToString(CultureInfo.InvariantCulture);
+ string BanCount = ((AdminToolbox.ATPlayerDict.ContainsKey(UserID) && AdminToolbox.ATPlayerDict[UserID].PlayerStats.BanCount > 0) ? AdminToolbox.ATPlayerDict[UserID].PlayerStats.BanCount : 0).ToString(CultureInfo.InvariantCulture);
+ if (AdminToolbox.ATPlayerDict.ContainsKey(UserID))
+ AdminToolbox.ATPlayerDict[UserID].JoinTime = DateTime.UtcNow;
+ string str = string.Join(SplitChar.ToString(), new string[] { Kills, TeamKills, Deaths, minutesPlayed, BanCount });
+ using (StreamWriter streamWriter = new StreamWriter(playerFilePath, false))
+ {
+ streamWriter.Write(str);
+ streamWriter.Close();
+ }
+ }
+ private void ReadFromFile(string UserID)
+ {
+ string playerFilePath = AdminToolbox.ATPlayerDict.ContainsKey(UserID) ? PlayerStatsPath + Path.DirectorySeparatorChar + UserID + ".txt" : PlayerStatsPath + Path.DirectorySeparatorChar + "server" + ".txt";
+ if (!File.Exists(playerFilePath))
+ PlayerStatsFileManager(UserID, PlayerFile.Write);
+ Debug("Reading: " + playerFilePath);
+ string[] fileStrings = (File.ReadAllLines(playerFilePath).Length > 0) ? File.ReadAllLines(playerFilePath) : new string[] { "0;0;0;0;0" };
+ string[] playerStats = fileStrings.FirstOrDefault().Split(SplitChar);
+ if (AdminToolbox.ATPlayerDict.ContainsKey(UserID))
+ {
+ PlayerSettings setting = AdminToolbox.ATPlayerDict[UserID];
+ setting.PlayerStats.Kills = (playerStats.Length > 0 && int.TryParse(playerStats[0], out int x0) && x0 > setting.PlayerStats.Kills) ? x0 : setting.PlayerStats.Kills;
+ setting.PlayerStats.TeamKills = (playerStats.Length > 1 && int.TryParse(playerStats[1], out int x1) && x1 > setting.PlayerStats.TeamKills) ? x1 : setting.PlayerStats.TeamKills;
+ setting.PlayerStats.Deaths = (playerStats.Length > 2 && int.TryParse(playerStats[2], out int x2) && x2 > setting.PlayerStats.Deaths) ? x2 : setting.PlayerStats.Deaths;
+ setting.PlayerStats.MinutesPlayed = (playerStats.Length > 3 && double.TryParse(playerStats[3], out double x3) && x3 > setting.PlayerStats.MinutesPlayed) ? x3 : setting.PlayerStats.MinutesPlayed;
+ setting.PlayerStats.BanCount = (playerStats.Length > 4 && int.TryParse(playerStats[4], out int x4) && x4 > setting.PlayerStats.BanCount) ? x4 : setting.PlayerStats.BanCount;
+ AdminToolbox.ATPlayerDict[UserID] = setting;
+ }
+ }
+
+ public static void RenameOldFilesToNewUserID()
+ {
+ Debug($"Entered {System.Reflection.MethodBase.GetCurrentMethod().Name} method");
+
+ if (!Config.GetBoolValue("admintoolbox_playerfiles", true))
+ {
+ Debug("PlayerfilesConfig was " + Config.GetBoolValue("admintoolbox_playerfiles", true) + ", returning");
+ return;
+ }
+ if (Config.GetBoolValue("admintoolbox_userfiles_convert", true))
+ {
+ Debug("Checking path: " + PlayerStatsPath);
+
+ string[] files = Directory.GetFiles(PlayerStatsPath, "*.txt").Where(n => !n.Contains("@")).ToArray();
+
+ if (files.Length > 0)
+ {
+ Info($"Files to rename: {files.Length}\n - Re-naming old file(s) to new UserID format");
+ if (files.Length > 2000)
+ {
+ Info(" - Large amount of files detected, this may take a moment...");
+ }
+ int fileCount = 0;
+ for (int i = files.Length - 1; i > -1; i--)
+ {
+ if (!Path.GetFileName(files[i]).Contains('@'))
+ {
+ fileCount++;
+ string _newpath = files[i].Substring(0, files[i].Length - 4) + "@steam.txt";
+ Debug(_newpath);
+ if (File.Exists(_newpath)) //At rare occations this file already exists
+ File.Delete(_newpath);
+ File.Move(files[i], _newpath);
+ }
+ }
+ Info($"- {fileCount} file(s) renamed to new UserID format");
+ }
+ else
+ {
+ Debug("No files to rename!");
+ }
+ }
+ else if (Config.GetBoolValue("admintoolbox_userfiles_revert", false))
+ {
+ string[] files = Directory.GetFiles(PlayerStatsPath);
+ if (files.Any(s => s.Contains('@')))
+ {
+ int fileCount = 0;
+ Info("- Reverting new file(s) to old SteamID format");
+
+ for (int i = files.Length - 1; i > -1; i--)
+ {
+ if (Path.GetFileName(files[i]).Contains('@'))
+ {
+ fileCount++;
+ AdminToolbox.singleton.Debug(files[i].Substring(0, files[i].Length - 4) + "@steam.txt");
+ File.Move(files[i], files[i].Substring(0, files[i].Length - 10) + ".txt");
+ }
+ }
+ Info($"- {fileCount} file(s) reverted");
+ }
+ }
+ }
+
+ ///
+ /// Read/Writes stats to/from for each UserID in the
+ ///
+ public static void ConvertOldFilesToJSON(string filePath = "")
+ {
+ int fileCount = 0;
+
+ string[] statsFiles = string.IsNullOrEmpty(filePath) ? Directory.GetFiles(PlayerStatsPath) : new string[] { filePath };
+ if (statsFiles.Where(f => !File.ReadAllText(f).StartsWith("{")).Count() >= 100)
+ {
+ Info("!Warning! The plugin will be converting old playerfiles to a new format, this might take some time");
+ }
+ if (statsFiles.Length > 0)
+ foreach (string path in statsFiles)
+ {
+ if (!File.Exists(path) || File.ReadAllLines(path).FirstOrDefault().StartsWith("{"))
+ continue;
+ try
+ {
+ string[] rawData = File.ReadAllText(path).Split(';');
+
+ PlayerStats ps = new PlayerStats();
+ ps.Kills = (rawData.Length > 0 && int.TryParse(rawData[0], out int x0) && x0 > ps.Kills) ? x0 : ps.Kills;
+ ps.TeamKills = (rawData.Length > 1 && int.TryParse(rawData[1], out int x1) && x1 > ps.TeamKills) ? x1 : ps.TeamKills;
+ ps.Deaths = (rawData.Length > 2 && int.TryParse(rawData[2], out int x2) && x2 > ps.Deaths) ? x2 : ps.Deaths;
+ ps.MinutesPlayed = (rawData.Length > 3 && double.TryParse(rawData[3].Replace(",", "."), NumberStyles.Number, CultureInfo.InvariantCulture, out double x3) && x3 > ps.MinutesPlayed && x3 < int.MaxValue) ? x3 : ps.MinutesPlayed;
+ ps.BanCount = (rawData.Length > 4 && int.TryParse(rawData[4], out int x4) && x4 > ps.BanCount) ? x4 : ps.BanCount;
+
+ int subtractedMinutes = (ps.MinutesPlayed < 0) ? (int)ps.MinutesPlayed : (int)-ps.MinutesPlayed;
+
+ SerializablePlayerClass playerClass = new SerializablePlayerClass(ps);
+ playerClass.PlayerInfo.FirstJoin = DateTime.UtcNow.Add(TimeSpan.FromMinutes(subtractedMinutes)).ToString(CultureInfo.InvariantCulture);
+
+ using (StreamWriter sw = new StreamWriter(path, false))
+ {
+ sw.WriteLine(Utf8Json.JsonSerializer.PrettyPrint(Utf8Json.JsonSerializer.Serialize(playerClass)));
+ }
+ fileCount++;
+ }
+ catch (Exception e)
+ {
+ Debug("Failed during convertion of: " + path + "\n" + e);
+ continue;
+ }
+ // Kills + TeamKills + Deaths + minutesPlayed + BanCount;
+ }
+ if (fileCount > 0)
+ Debug(fileCount + " file(s) converted to new JSON format!");
+ }
+
+ ///
+ /// The class uses for JSON Serialize/Deserialize operations
+ ///
+ public class SerializablePlayerClass
+ {
+ public PlayerInfo PlayerInfo = new PlayerInfo();
+ public PlayerStats PlayerStats = new PlayerStats();
+
+ public SerializablePlayerClass() { }
+ public SerializablePlayerClass(PlayerStats stats) => this.PlayerStats = stats;
+ public SerializablePlayerClass(PlayerSettings setting)
+ {
+ this.PlayerInfo = setting.PlayerInfo;
+ this.PlayerStats = setting.PlayerStats;
+ }
+ }
+
+ ///
+ /// Writes current version to
+ ///
+ public static void WriteVersionToFile()
+ {
+ string path = GetFolderPath(Folder.AppData);
+ if (Directory.Exists(path))
+ {
+ try
+ {
+ string text = "at_version=" + AdminToolbox.singleton.Details.version.Split('-').FirstOrDefault();
+ using (StreamWriter streamWriter = new StreamWriter(path + "at_version.md", false))
+ {
+ streamWriter.Write(text);
+ }
+ }
+ catch(Exception e)
+ {
+ Debug("Failed writing version to file!\n" + e);
+ }
+ try
+ {
+ if (File.Exists(path + "n_at_version.md"))
+ File.Delete(path + "n_at_version.md");
+ }
+ catch (Exception e)
+ {
+ Debug("Failed deleting temp version file!\n" + e);
+ }
+ }
+ else
+ Info("Could not find SCP Secret Lab folder!");
+ }
+
+ internal static void AddMissingPlayerVariables()
+ {
+ if (PluginManager.Manager.Server.GetPlayers().Count == 0)
+ return;
+ AddMissingPlayerVariables(PluginManager.Manager.Server.GetPlayers());
+ }
+ internal static void AddMissingPlayerVariables(Player player)
+ => AddMissingPlayerVariables(new List() { player });
+ internal static void AddMissingPlayerVariables(List players)
+ => AddMissingPlayerVariables(players.ToArray());
+ internal static void AddMissingPlayerVariables(Player[] players)
+ {
+ Player[] allPlayers = PluginManager.Manager.Server.GetPlayers().ToArray();
+ if (allPlayers.Length == 0)
+ {
+ return;
+ }
+ else if (players == null || players.Length < 1)
+ {
+ players = allPlayers;
+ }
+ if (players.Length > 0)
+ {
+ foreach (Player player in players)
+ {
+ if (player != null && !string.IsNullOrEmpty(player.UserID))
+ {
+ AddToPlayerDict(player);
+ }
+ }
+ }
+ }
+ private static void AddToPlayerDict(Player player)
+ {
+ if (player != null && player is Player p &&
+ !string.IsNullOrEmpty(p.UserID) && !AdminToolbox.ATPlayerDict.ContainsKey(p.UserID))
+ {
+ AdminToolbox.ATPlayerDict.Add(p.UserID, new PlayerSettings(p.UserID));
+ }
+ }
+ }
+}
diff --git a/AdminToolbox/AdminToolbox/Managers/ATFileManager.cs b/AdminToolbox/AdminToolbox/Managers/ATFileManager.cs
deleted file mode 100644
index 9066135..0000000
--- a/AdminToolbox/AdminToolbox/Managers/ATFileManager.cs
+++ /dev/null
@@ -1,426 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using Smod2;
-using Smod2.API;
-
-namespace AdminToolbox.Managers
-{
- using API;
-
- internal enum Folder
- {
- AppData,
- ATRoot,
- PlayerFiles,
- Logs,
- Warps
- }
- ///
- /// Contains all -related functionality
- ///
- ///
- public class ATFileManager
- {
- private static IConfigFile Config => ConfigManager.Manager.Config;
- private static int Port => PluginManager.Manager.Server.Port;
-
- internal const char SplitChar = ';';
-
- internal bool ProcessingCollection = false;
-
- ///
- /// for
- ///
- public enum PlayerFile
- {
- Read = 0,
- Write = 1
- }
-
- private static string GetATFolderPath()
- {
- string cnfgpath = Config.GetStringValue("admintoolbox_folder_path", string.Empty);
- if (!string.IsNullOrEmpty(cnfgpath))
- {
- if (!cnfgpath.EndsWith(Path.DirectorySeparatorChar.ToString()))
- cnfgpath += Path.DirectorySeparatorChar;
- cnfgpath += "AdminToolbox" + Path.DirectorySeparatorChar;
- }
- else
- {
- cnfgpath = FileManager.GetAppFolder(addSeparator: true) + "AdminToolbox" + Path.DirectorySeparatorChar;
- }
- if (!Directory.Exists(cnfgpath))
- Directory.CreateDirectory(cnfgpath);
- return cnfgpath;
- }
-
- internal static string GetFolderPath(Folder folder = Folder.ATRoot)
- {
-
- string ret = GetATFolderPath();
- switch (folder)
- {
- case Folder.PlayerFiles:
- ret += "PlayerStats" + Path.DirectorySeparatorChar;
- if (!Directory.Exists(ret))
- Directory.CreateDirectory(ret);
- if (Config.GetBoolValue("admintoolbox_stats_unified", true))
- ret += "Global" + Path.DirectorySeparatorChar;
- else
- ret += Port + Path.DirectorySeparatorChar;
- break;
-
- case Folder.Logs:
- ret += "ServerLogs" + Path.DirectorySeparatorChar;
- break;
-
- case Folder.Warps:
- ret += "WarpPoints" + Path.DirectorySeparatorChar;
- break;
-
- case Folder.AppData:
- return FileManager.GetAppFolder(addSeparator: true);
-
- case Folder.ATRoot:
- default:
- break;
- }
- if (!Directory.Exists(ret))
- Directory.CreateDirectory(ret);
- return ret;
- }
-
- internal static string AdminToolboxFolder =>
- GetATFolderPath();
-
- internal static string AdminToolboxPlayerStats =>
- GetFolderPath(Folder.PlayerFiles);
-
- internal static string AdminToolboxLogs =>
- GetFolderPath(Folder.Logs);
-
- ///
- /// Read/Writes stats to/from
- ///
- public void PlayerStatsFileManager(PlayerFile FileOperation = PlayerFile.Read) => PlayerStatsFileManager(new string[] { }, FileOperation);
-
- ///
- /// Read/Writes the 's stats to/from
- ///
- public void PlayerStatsFileManager(string UserId, PlayerFile FileOperation = PlayerFile.Write) => PlayerStatsFileManager(new string[] { UserId }, FileOperation);
-
- ///
- /// Read/Writes stats to/from
- ///
- public void PlayerStatsFileManager(Player player, PlayerFile FileOperation = PlayerFile.Write) => PlayerStatsFileManager(new string[] { player.UserId }, FileOperation);
-
- ///
- /// Read/Writes stats to/from for each in the
- ///
- public void PlayerStatsFileManager(List playerList, PlayerFile FileOperation = PlayerFile.Read)
- {
- if (playerList != null && playerList.Count > 0)
- PlayerStatsFileManager(playerList.Select(p => p.UserId).ToArray(), FileOperation);
- else
- PlayerStatsFileManager(FileOperation);
- }
-
- ///
- /// Read/Writes stats to/from for each UserId in the
- ///
- public void PlayerStatsFileManager(List UserIdList, PlayerFile FileOperation = PlayerFile.Read)
- {
- if (UserIdList != null && UserIdList.Count > 0)
- PlayerStatsFileManager(UserIdList.ToArray(), FileOperation);
- else
- PlayerStatsFileManager(new string[0], FileOperation);
- }
-
- ///
- /// Read/Writes stats to/from for each UserId in the
- ///
- public void PlayerStatsFileManager(string[] UserIdArray, PlayerFile FileOperation = PlayerFile.Read)
- {
- if (!Config.GetBoolValue("admintoolbox_playerfiles", false))
- return;
- if (Directory.Exists(AdminToolboxFolder))
- {
- if (!Directory.Exists(AdminToolboxFolder))
- Directory.CreateDirectory(AdminToolboxFolder);
- if (!Directory.Exists(AdminToolboxPlayerStats))
- Directory.CreateDirectory(AdminToolboxPlayerStats);
-
- ProcessingCollection = true;
-
- if (UserIdArray != null && UserIdArray.Length > 0)
- foreach (string sid in UserIdArray)
- ReadWriteHandler(sid, FileOperation);
- else
- {
- string[] keys = AdminToolbox.ATPlayerDict.Keys.ToArray();
- foreach (string UserId in keys)
- ReadWriteHandler(UserId, FileOperation);
- }
-
- ProcessingCollection = false;
-
-
- void ReadWriteHandler(string UserId, PlayerFile Operation)
- {
- if (string.IsNullOrEmpty(UserId)) return;
- if (!AdminToolbox.ATPlayerDict.ContainsKey(UserId))
- {
- AdminToolbox.AddMissingPlayerVariables(PluginManager.Manager.Server.GetPlayers(UserId));
- return;
- }
- switch (Operation)
- {
- case PlayerFile.Write:
- WriteToFile(UserId);
- break;
- case PlayerFile.Read:
- default:
- ReadFromFile(UserId);
- break;
- }
- }
-
- #region NewFilesStuff
- /*
- void NewWriteToFile(string UserId)
- {
- if (!AdminToolbox.ATPlayerDict.ContainsKey(UserId)) return;
- string playerFilePath = AdminToolboxPlayerStats + UserId + ".txt";
- if (!File.Exists(playerFilePath))
- File.Create(playerFilePath).Dispose();
-
- if (File.ReadAllLines(playerFilePath).Length <= 2)
- ConvertOldFilesToJSON(playerFilePath);
- SerilizablePlayerClass pl = new SerilizablePlayerClass(AdminToolbox.ATPlayerDict[UserId]);
-
- if (string.IsNullOrEmpty(pl.PlayerInfo.FirstJoin))
- pl.PlayerInfo.FirstJoin = DateTime.Now.AddMinutes(-pl.PlayerStats.MinutesPlayed).ToString(CultureInfo.InvariantCulture);
-
- using (StreamWriter sw = new StreamWriter(playerFilePath, false))
- {
- sw.WriteLine(JsonConvert.SerializeObject(pl, Formatting.Indented));
- }
-
- NewReadFromFile(UserId);
- }
- void NewReadFromFile(string UserId)
- {
- if (!AdminToolbox.ATPlayerDict.ContainsKey(UserId)) return;
- string playerFilePath = AdminToolboxPlayerStats + UserId + ".txt";
- if (!File.Exists(playerFilePath))
- WriteToFile(UserId);
-
- if (File.ReadAllLines(playerFilePath).FirstOrDefault().Split(splitChar).Length > 3)
- ConvertOldFilesToJSON(playerFilePath);
-
- string rawJSON = File.ReadAllText(playerFilePath);
- SerilizablePlayerClass pl = JsonConvert.DeserializeObject(rawJSON);
-
- PlayerSettings playersetting = AdminToolbox.ATPlayerDict[UserId];
-
- if (string.IsNullOrEmpty(pl.PlayerInfo.FirstJoin))
- playersetting.PlayerInfo.FirstJoin = DateTime.Now.AddMinutes(-pl.PlayerStats.MinutesPlayed).ToString(CultureInfo.InvariantCulture);
- playersetting.PlayerStats = pl.PlayerStats;
- }
- */
- #endregion
-
- void WriteToFile(string UserId)
- {
- if (!AdminToolbox.ATPlayerDict.ContainsKey(UserId))
- {
- if (PluginManager.Manager.Server.GetPlayers(UserId).Count < 1) return;
- AdminToolbox.AddMissingPlayerVariables(PluginManager.Manager.Server.GetPlayers(UserId).FirstOrDefault());
- }
- if (!AdminToolbox.ATPlayerDict.ContainsKey(UserId)) return;
- string playerFilePath = AdminToolbox.ATPlayerDict.ContainsKey(UserId) ? AdminToolboxPlayerStats + Path.DirectorySeparatorChar + UserId + ".txt" : AdminToolboxPlayerStats + Path.DirectorySeparatorChar + "server" + ".txt";
- if (!File.Exists(playerFilePath))
- File.Create(playerFilePath).Dispose();
- AdminToolbox.singleton.Debug("Writing: " + playerFilePath);
-
- PlayerSettings setting = AdminToolbox.ATPlayerDict.ContainsKey(UserId) ? AdminToolbox.ATPlayerDict[UserId] : new API.PlayerSettings(UserId);
- int Kills = (AdminToolbox.ATPlayerDict.ContainsKey(UserId) && AdminToolbox.ATPlayerDict[UserId].PlayerStats.Kills > 0) ? AdminToolbox.ATPlayerDict[UserId].PlayerStats.Kills : 0;
- int TeamKills = (AdminToolbox.ATPlayerDict.ContainsKey(UserId) && AdminToolbox.ATPlayerDict[UserId].PlayerStats.TeamKills > 0) ? AdminToolbox.ATPlayerDict[UserId].PlayerStats.TeamKills : 0;
- int Deaths = (AdminToolbox.ATPlayerDict.ContainsKey(UserId) && AdminToolbox.ATPlayerDict[UserId].PlayerStats.Deaths > 0) ? AdminToolbox.ATPlayerDict[UserId].PlayerStats.Deaths : 0;
- double minutesPlayed = (AdminToolbox.ATPlayerDict.ContainsKey(UserId) && AdminToolbox.ATPlayerDict[UserId].PlayerStats.MinutesPlayed > 0) ? DateTime.Now.Subtract(AdminToolbox.ATPlayerDict[UserId].JoinTime).TotalMinutes + AdminToolbox.ATPlayerDict[UserId].PlayerStats.MinutesPlayed : 0;
- int BanCount = (AdminToolbox.ATPlayerDict.ContainsKey(UserId) && AdminToolbox.ATPlayerDict[UserId].PlayerStats.BanCount > 0) ? AdminToolbox.ATPlayerDict[UserId].PlayerStats.BanCount : 0;
- if (AdminToolbox.ATPlayerDict.ContainsKey(UserId)) AdminToolbox.ATPlayerDict[UserId].JoinTime = DateTime.Now;
- string str = string.Empty + Kills + SplitChar + TeamKills + SplitChar + Deaths + SplitChar + minutesPlayed + SplitChar + BanCount;
- using (StreamWriter streamWriter = new StreamWriter(playerFilePath, false))
- {
- streamWriter.Write(str);
- streamWriter.Close();
- }
- ReadFromFile(UserId);
- }
- void ReadFromFile(string UserId)
- {
- string playerFilePath = AdminToolbox.ATPlayerDict.ContainsKey(UserId) ? AdminToolboxPlayerStats + Path.DirectorySeparatorChar + UserId + ".txt" : AdminToolboxPlayerStats + Path.DirectorySeparatorChar + "server" + ".txt";
- if (!File.Exists(playerFilePath))
- PlayerStatsFileManager(new List { UserId }, PlayerFile.Write);
- AdminToolbox.singleton.Debug("Reading: " + playerFilePath);
- string[] fileStrings = (File.ReadAllLines(playerFilePath).Length > 0) ? File.ReadAllLines(playerFilePath) : new string[] { "0;0;0;0;0" };
- string[] playerStats = fileStrings.FirstOrDefault().Split(SplitChar);
- if (AdminToolbox.ATPlayerDict.ContainsKey(UserId))
- {
- PlayerSettings setting = AdminToolbox.ATPlayerDict[UserId];
- setting.PlayerStats.Kills = (playerStats.Length > 0 && int.TryParse(playerStats[0], out int x0) && x0 > setting.PlayerStats.Kills) ? x0 : setting.PlayerStats.Kills;
- setting.PlayerStats.TeamKills = (playerStats.Length > 1 && int.TryParse(playerStats[1], out int x1) && x1 > setting.PlayerStats.TeamKills) ? x1 : setting.PlayerStats.TeamKills;
- setting.PlayerStats.Deaths = (playerStats.Length > 2 && int.TryParse(playerStats[2], out int x2) && x2 > setting.PlayerStats.Deaths) ? x2 : setting.PlayerStats.Deaths;
- setting.PlayerStats.MinutesPlayed = (playerStats.Length > 3 && double.TryParse(playerStats[3], out double x3) && x3 > setting.PlayerStats.MinutesPlayed) ? x3 : setting.PlayerStats.MinutesPlayed;
- setting.PlayerStats.BanCount = (playerStats.Length > 4 && int.TryParse(playerStats[4], out int x4) && x4 > setting.PlayerStats.BanCount) ? x4 : setting.PlayerStats.BanCount;
- AdminToolbox.ATPlayerDict[UserId] = setting;
- }
- }
- }
- }
-
- public static void ConvertOldFilesToNewUserID()
- {
- if (!Config.GetBoolValue("admintoolbox_playerfiles", false))
- return;
- if (Config.GetBoolValue("admintoolbox_userfiles_convert", true))
- {
- string[] files = Directory.GetFiles(AdminToolboxPlayerStats);
- if (files.Any(s => !s.Contains('@')))
- {
- int x = 0;
- AdminToolbox.singleton.Info("(File Manager) - Converting old files to new UserID format");
- if (files.Length > 5000)
- {
- AdminToolbox.singleton.Info("(File Manager) - Large amount of files detected, this may take a moment...");
- }
- for (int i = files.Length - 1; i > -1; i--)
- {
- if (!Path.GetFileName(files[i]).Contains('@'))
- {
- x++;
- AdminToolbox.singleton.Debug(files[i].Substring(0, files[i].Length - 4) + "@steam.txt");
- File.Move(files[i], files[i].Substring(0, files[i].Length - 4) + "@steam.txt");
- }
- }
- AdminToolbox.singleton.Info($"(File Manager) - {x} files converted");
- }
- }
- else if (Config.GetBoolValue("admintoolbox_userfiles_revert", false))
- {
- string[] files = Directory.GetFiles(AdminToolboxPlayerStats);
- if (files.Any(s => s.Contains('@')))
- {
- int x = 0;
- AdminToolbox.singleton.Info("(File Manager) - Reverting new files to old SteamID format");
-
- for (int i = files.Length - 1; i > -1; i--)
- {
- if (Path.GetFileName(files[i]).Contains('@'))
- {
- x++;
- AdminToolbox.singleton.Debug(files[i].Substring(0, files[i].Length - 4) + "@steam.txt");
- File.Move(files[i], files[i].Substring(0, files[i].Length - 10) + ".txt");
- }
- }
- AdminToolbox.singleton.Info($"(File Manager) - {x} files reverted");
- }
- }
- }
-
- ///
- /// Read/Writes stats to/from for each UserId in the
- ///
- public static void ConvertOldFilesToJSON(string file = "")
- {
- return;
-#pragma warning disable CS0162 // Unreachable code detected
- int x = 0;
-
- string[] files = string.IsNullOrEmpty(file) ? Directory.GetFiles(AdminToolboxPlayerStats) : new string[] { file };
- if (files.Where(f => !File.ReadAllText(f).StartsWith("{")).Count() >= 100)
- {
- AdminToolbox.singleton.Info("Warning: The plugin will be converting old playerfiles to a new format." + "\n" + "Beware that this might take some time");
- }
- if (files.Length > 0)
- foreach (string path in files)
- {
- if (!File.Exists(path) || File.ReadAllLines(path).FirstOrDefault().StartsWith("{")) continue;
- try
- {
- string[] rawData = File.ReadAllText(path).Split(';');
-
- PlayerStats ps = new PlayerStats();
- ps.Kills = (rawData.Length > 0 && int.TryParse(rawData[0], out int x0) && x0 > ps.Kills) ? x0 : ps.Kills;
- ps.TeamKills = (rawData.Length > 1 && int.TryParse(rawData[1], out int x1) && x1 > ps.TeamKills) ? x1 : ps.TeamKills;
- ps.Deaths = (rawData.Length > 2 && int.TryParse(rawData[2], out int x2) && x2 > ps.Deaths) ? x2 : ps.Deaths;
- ps.MinutesPlayed = (rawData.Length > 3 && double.TryParse(rawData[3].Replace(",", "."), NumberStyles.Number, CultureInfo.InvariantCulture, out double x3) && x3 > ps.MinutesPlayed && x3 < int.MaxValue) ? x3 : ps.MinutesPlayed;
- ps.BanCount = (rawData.Length > 4 && int.TryParse(rawData[4], out int x4) && x4 > ps.BanCount) ? x4 : ps.BanCount;
-
- int subtractedMinutes = (ps.MinutesPlayed < 0) ? (int)ps.MinutesPlayed : (int)-ps.MinutesPlayed;
-
- SerilizablePlayerClass playerClass = new SerilizablePlayerClass(ps);
- playerClass.PlayerInfo.FirstJoin = DateTime.Now.Add(TimeSpan.FromMinutes(subtractedMinutes)).ToString(CultureInfo.InvariantCulture);
-
- using (StreamWriter sw = new StreamWriter(path, false))
- {
- //sw.WriteLine(UnityEngine.JsonUtility.ToJson(playerClass, true));
- }
- x++;
- }
- catch (Exception e)
- {
- AdminToolbox.singleton.Debug("Failed during convertion of: " + path);
- AdminToolbox.singleton.Debug(e.StackTrace);
- continue;
- }
- // Kills + TeamKills + Deaths + minutesPlayed + BanCount;
- }
- if (x > 0)
- AdminToolbox.singleton.Debug(x + " files converted to new JSON format!");
-#pragma warning restore CS0162 // Unreachable code detected
- }
-
- ///
- /// The class uses for JSON Serialize/Deserialize operations
- ///
- public class SerilizablePlayerClass
- {
- public PlayerInfo PlayerInfo = new PlayerInfo();
- public PlayerStats PlayerStats = new PlayerStats();
-
- public SerilizablePlayerClass() { }
- public SerilizablePlayerClass(PlayerStats stats) => this.PlayerStats = stats;
- public SerilizablePlayerClass(PlayerSettings setting)
- {
- this.PlayerInfo = setting.PlayerInfo;
- this.PlayerStats = setting.PlayerStats;
- }
- }
-
- ///
- /// Writes current version to
- ///
- public static void WriteVersionToFile()
- {
- string path = GetFolderPath(Folder.AppData);
- if (Directory.Exists(path))
- {
- string text = "at_version=" + AdminToolbox.singleton.Details.version.Split('-').FirstOrDefault();
- using (StreamWriter streamWriter = new StreamWriter(path + "at_version.md", false))
- {
- streamWriter.Write(text);
- }
- if (File.Exists(path + "n_at_version.md"))
- File.Delete(path + "n_at_version.md");
- }
- else
- AdminToolbox.singleton.Info("Could not find SCP Secret Lab folder!");
- }
- }
-}
diff --git a/AdminToolbox/AdminToolbox/Managers/LogManager.cs b/AdminToolbox/AdminToolbox/Managers/LogManager.cs
index ae17da3..f833c2c 100644
--- a/AdminToolbox/AdminToolbox/Managers/LogManager.cs
+++ b/AdminToolbox/AdminToolbox/Managers/LogManager.cs
@@ -32,11 +32,11 @@ internal class LogData
internal string _logStartTime;
private static string
- AppFolder => ATFileManager.GetFolderPath(Folder.AppData);
+ AppFolder => ATFile.GetFolderPath(Folder.AppData);
private static string
- AdminToolboxFolder => ATFileManager.AdminToolboxFolder;
+ AdminToolboxFolder => ATFile.MainPath;
private static string
- AdminToolboxLogs => ATFileManager.AdminToolboxLogs;
+ AdminToolboxLogs => ATFile.LogPath;
///
/// Enum used by
@@ -102,7 +102,7 @@ private void AddLog(string msg, ServerLogType type)
}
}
- internal void SetLogStartTime() => _logStartTime = DateTime.Now.Year.ToString() + "-" + ((DateTime.Now.Month >= 10) ? DateTime.Now.Month.ToString() : ("0" + DateTime.Now.Month.ToString())) + "-" + ((DateTime.Now.Day >= 10) ? DateTime.Now.Day.ToString() : ("0" + DateTime.Now.Day.ToString())) + " " + ((DateTime.Now.Hour >= 10) ? DateTime.Now.Hour.ToString() : ("0" + DateTime.Now.Hour.ToString())) + "." + ((DateTime.Now.Minute >= 10) ? DateTime.Now.Minute.ToString() : ("0" + DateTime.Now.Minute.ToString())) + "." + ((DateTime.Now.Second >= 10) ? DateTime.Now.Second.ToString() : ("0" + DateTime.Now.Second.ToString()));
+ internal void SetLogStartTime() => _logStartTime = DateTime.UtcNow.Year.ToString() + "-" + ((DateTime.UtcNow.Month >= 10) ? DateTime.UtcNow.Month.ToString() : ("0" + DateTime.UtcNow.Month.ToString())) + "-" + ((DateTime.UtcNow.Day >= 10) ? DateTime.UtcNow.Day.ToString() : ("0" + DateTime.UtcNow.Day.ToString())) + " " + ((DateTime.UtcNow.Hour >= 10) ? DateTime.UtcNow.Hour.ToString() : ("0" + DateTime.UtcNow.Hour.ToString())) + "." + ((DateTime.UtcNow.Minute >= 10) ? DateTime.UtcNow.Minute.ToString() : ("0" + DateTime.UtcNow.Minute.ToString())) + "." + ((DateTime.UtcNow.Second >= 10) ? DateTime.UtcNow.Second.ToString() : ("0" + DateTime.UtcNow.Second.ToString()));
private bool CheckExistingFolders()
{
@@ -142,7 +142,7 @@ public void ManageDatedATLogs(uint hoursOld)
if (files.Length > 0)
foreach (string path in files)
{
- int num = (int)(DateTime.Now - File.GetCreationTime(path)).TotalHours;
+ int num = (int)(DateTime.UtcNow - new DateTime(File.GetCreationTime(path).ToFileTimeUtc())).TotalHours;
AdminToolbox.singleton.Debug(path + "\nHours Old: " + num);
if (num > configInt)
{
diff --git a/AdminToolbox/AdminToolbox/Managers/WarpManager.cs b/AdminToolbox/AdminToolbox/Managers/WarpManager.cs
index 312493b..746e6f8 100644
--- a/AdminToolbox/AdminToolbox/Managers/WarpManager.cs
+++ b/AdminToolbox/AdminToolbox/Managers/WarpManager.cs
@@ -2,7 +2,6 @@
using System.IO;
using System.Linq;
using Smod2;
-using Newtonsoft.Json;
namespace AdminToolbox.Managers
{
@@ -16,9 +15,7 @@ public class WarpManager
{
private static AdminToolbox Plugin => AdminToolbox.singleton;
- private static int Port => PluginManager.Manager.Server.Port;
-
- private static string WarpPointsFolder => ATFileManager.GetFolderPath(Folder.Warps);
+ private static string WarpPointsFolder => ATFile.GetFolderPath(Folder.Warps);
private static string WarpFilePath => WarpPointsFolder + "Global.txt";
@@ -83,7 +80,7 @@ public void RemoveUndergroundWarps()
public bool WriteWarpsToFile(WarpPoint[] warpPoints = null)
{
Debug("Entered WriteToFile");
- if (!ConfigManager.Manager.Config.GetBoolValue("admintoolbox_warpfiles", false))
+ if (!ConfigManager.Manager.Config.GetBoolValue("admintoolbox_warpfiles", true))
return false;
try
{
@@ -100,7 +97,8 @@ public bool WriteWarpsToFile(WarpPoint[] warpPoints = null)
Debug("Attempting JSON Serialize " + warparray.Length + " array items!");
foreach (WarpPoint w in warparray)
Debug(w.Name);
- jsonData = JsonConvert.SerializeObject(warparray, Formatting.Indented);
+ jsonData = Utf8Json.JsonSerializer.PrettyPrint(Utf8Json.JsonSerializer.Serialize(warparray));
+ //JsonConvert.SerializeObject(warparray, Formatting.Indented);
//jsonData = JsonUtility.ToJson(warparray, true);
Debug("Finished JSON Serialize");
bool b1 = File.Exists(WarpFilePath);
@@ -121,7 +119,7 @@ public bool WriteWarpsToFile(WarpPoint[] warpPoints = null)
catch (Exception e)
{
Plugin.Info("Failed during writing of warpfile!");
- Debug("Error occured during writing to file: " + e.Message);
+ Debug("Error occured during writing to file: " + e);
return false;
}
}
@@ -132,7 +130,7 @@ public bool WriteWarpsToFile(WarpPoint[] warpPoints = null)
public Dictionary ReadWarpsFromFile()
{
Debug("Entered ReadFromFile");
- if (!ConfigManager.Manager.Config.GetBoolValue("admintoolbox_warpfiles", false))
+ if (!ConfigManager.Manager.Config.GetBoolValue("admintoolbox_warpfiles", true))
return presetWarps;
try
{
@@ -156,8 +154,9 @@ public Dictionary ReadWarpsFromFile()
return presetWarps;
}
Debug("Converting JSON to array");
- WarpPoint[] warpArray = JsonConvert.DeserializeObject(jsonData);
- //WarpPoint[] warpArray = UnityEngine.JsonUtility.FromJson(jsonData);
+
+ WarpPoint[] warpArray = Utf8Json.JsonSerializer.Deserialize(jsonData);
+
if (warpArray.Length > 0)
{
Debug("Populating dict with json array");