ReSharper code reformat to match naming conventions and stuff

This commit is contained in:
Lucas Nicodemus 2011-12-30 14:38:04 -07:00
parent 1147788154
commit c6abbfe4d2
45 changed files with 11639 additions and 11342 deletions

View file

@ -30,7 +30,8 @@ namespace TShockAPI
public int Interval { get; set; }
public int KeepFor { get; set; }
DateTime lastbackup = DateTime.UtcNow;
private DateTime lastbackup = DateTime.UtcNow;
public BackupManager(string path)
{
BackupPath = path;
@ -38,10 +39,7 @@ namespace TShockAPI
public bool IsBackupTime
{
get
{
return (Interval > 0) && ((DateTime.UtcNow - lastbackup).TotalMinutes >= Interval);
}
get { return (Interval > 0) && ((DateTime.UtcNow - lastbackup).TotalMinutes >= Interval); }
}
public void Backup()
@ -51,7 +49,7 @@ namespace TShockAPI
ThreadPool.QueueUserWorkItem(DeleteOld);
}
void DoBackup(object o)
private void DoBackup(object o)
{
try
{
@ -88,7 +86,7 @@ namespace TShockAPI
}
}
void DeleteOld(object o)
private void DeleteOld(object o)
{
if (KeepFor <= 0)
return;

View file

@ -31,10 +31,12 @@ using TShockAPI.DB;
namespace TShockAPI
{
public delegate void CommandDelegate(CommandArgs args);
public class CommandArgs : EventArgs
{
public string Message { get; private set; }
public TSPlayer Player { get; private set; }
/// <summary>
/// Parameters passed to the arguement. Does not include the command name.
/// IE '/kick "jerk face"' will only have 1 argument
@ -53,9 +55,14 @@ namespace TShockAPI
Parameters = args;
}
}
public class Command
{
public string Name { get { return Names[0]; } }
public string Name
{
get { return Names[0]; }
}
public List<string> Names { get; protected set; }
public bool DoLog { get; set; }
public string Permission { get; protected set; }
@ -66,6 +73,7 @@ namespace TShockAPI
{
Permission = permissionneeded;
}
public Command(CommandDelegate cmd, params string[] names)
{
if (names == null || names.Length < 1)
@ -104,11 +112,13 @@ namespace TShockAPI
return ply.Group.HasPermission(Permission);
}
}
public static class Commands
{
public static List<Command> ChatCommands = new List<Command>();
delegate void AddChatCommand(string permission, CommandDelegate command, params string[] names);
private delegate void AddChatCommand(string permission, CommandDelegate command, params string[] names);
public static void InitCommands()
{
//When adding new perm in here, add new perm to CommandList in DBEditor
@ -321,10 +331,10 @@ namespace TShockAPI
public static void AttemptLogin(CommandArgs args)
{
if (args.Player.LoginAttempts > TShock.Config.MaximumLoginAttempts && (TShock.Config.MaximumLoginAttempts != -1))
{
Log.Warn(args.Player.IP + "(" + args.Player.Name + ") had " + TShock.Config.MaximumLoginAttempts + " or more invalid login attempts and was kicked automatically.");
Log.Warn(args.Player.IP + "(" + args.Player.Name + ") had " + TShock.Config.MaximumLoginAttempts +
" or more invalid login attempts and was kicked automatically.");
TShock.Utils.Kick(args.Player, "Too many invalid login attempts.");
}
@ -390,7 +400,6 @@ namespace TShockAPI
args.Player.SendMessage("There was an error processing your request.", Color.Red);
Log.Error(ex.ToString());
}
}
private static void PasswordUser(CommandArgs args)
@ -410,12 +419,14 @@ namespace TShockAPI
else
{
args.Player.SendMessage("You failed to change your password!", Color.Red);
Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for Account: " + user.Name);
Log.ConsoleError(args.Player.IP + " named " + args.Player.Name + " failed to change password for Account: " +
user.Name);
}
}
else
{
args.Player.SendMessage("Not Logged in or Invalid syntax! Proper syntax: /password <oldpassword> <newpassword>", Color.Red);
args.Player.SendMessage("Not Logged in or Invalid syntax! Proper syntax: /password <oldpassword> <newpassword>",
Color.Red);
}
}
catch (UserManagerException ex)
@ -567,7 +578,6 @@ namespace TShockAPI
try
{
if (args.Parameters.Count == 3)
{
args.Player.SendMessage("Changed the password of " + user.Name + "!", Color.Green);
@ -596,18 +606,19 @@ namespace TShockAPI
try
{
if (args.Parameters.Count == 3)
{
if (!string.IsNullOrEmpty(user.Address))
{
args.Player.SendMessage("IP Address " + user.Address + " has been changed to group " + args.Parameters[2] + "!", Color.Green);
args.Player.SendMessage("IP Address " + user.Address + " has been changed to group " + args.Parameters[2] + "!",
Color.Green);
TShock.Users.SetUserGroup(user, args.Parameters[2]);
Log.ConsoleInfo(args.Player.Name + " changed IP Address " + user.Address + " to group " + args.Parameters[2]);
}
else
{
args.Player.SendMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!", Color.Green);
args.Player.SendMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!",
Color.Green);
TShock.Users.SetUserGroup(user, args.Parameters[2]);
Log.ConsoleInfo(args.Player.Name + " changed Account " + user.Name + " to group " + args.Parameters[2]);
}
@ -636,9 +647,11 @@ namespace TShockAPI
args.Player.SendMessage("Invalid user syntax. Try /user help.", Color.Red);
}
}
#endregion
#region Stupid commands
public static void ServerInfo(CommandArgs args)
{
args.Player.SendMessage("Memory usage: " + Process.GetCurrentProcess().WorkingSet64);
@ -648,6 +661,7 @@ namespace TShockAPI
args.Player.SendMessage("Proc count: " + Environment.ProcessorCount);
args.Player.SendMessage("Machine name: " + Environment.MachineName);
}
#endregion
#region Player Management Commands
@ -701,7 +715,9 @@ namespace TShockAPI
}
else
{
string reason = args.Parameters.Count > 1 ? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)) : "Misbehaviour.";
string reason = args.Parameters.Count > 1
? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1))
: "Misbehaviour.";
if (!TShock.Utils.Kick(players[0], reason))
{
args.Player.SendMessage("You can't kick another admin!", Color.Red);
@ -734,7 +750,9 @@ namespace TShockAPI
}
else
{
string reason = args.Parameters.Count > 1 ? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)) : "Misbehaviour.";
string reason = args.Parameters.Count > 1
? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1))
: "Misbehaviour.";
if (!TShock.Utils.Ban(players[0], reason))
{
args.Player.SendMessage("You can't ban another admin!", Color.Red);
@ -756,7 +774,9 @@ namespace TShockAPI
}
string ip = args.Parameters[0];
string reason = args.Parameters.Count > 1 ? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)) : "Manually added IP address ban.";
string reason = args.Parameters.Count > 1
? String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1))
: "Manually added IP address ban.";
TShock.Bans.AddBan(ip, "", reason);
}
@ -799,7 +819,8 @@ namespace TShockAPI
}
}
static int ClearBansCode = -1;
private static int ClearBansCode = -1;
private static void ClearBans(CommandArgs args)
{
if (args.Parameters.Count < 1 && ClearBansCode == -1)
@ -1241,13 +1262,15 @@ namespace TShockAPI
else
{
var npc = npcs[0];
if (npc.type >= 1 && npc.type < Main.maxNPCTypes && npc.type != 113) //Do not allow WoF to spawn, in certain conditions may cause loops in client
if (npc.type >= 1 && npc.type < Main.maxNPCTypes && npc.type != 113)
//Do not allow WoF to spawn, in certain conditions may cause loops in client
{
TSPlayer.Server.SpawnNPC(npc.type, npc.name, amount, args.Player.TileX, args.Player.TileY, 50, 20);
TShock.Utils.Broadcast(string.Format("{0} was spawned {1} time(s).", npc.name, amount));
}
else if (npc.type == 113)
args.Player.SendMessage("Sorry, you can't spawn Wall of Flesh! Try /wof instead."); // Maybe perhaps do something with WorldGen.SpawnWoF?
args.Player.SendMessage("Sorry, you can't spawn Wall of Flesh! Try /wof instead.");
// Maybe perhaps do something with WorldGen.SpawnWoF?
else
args.Player.SendMessage("Invalid mob type!", Color.Red);
}
@ -1782,7 +1805,8 @@ namespace TShockAPI
FileTools.SetupConfig();
TShock.Groups.LoadPermisions();
TShock.Regions.ReloadAllRegions();
args.Player.SendMessage("Configuration, Permissions, and Regions reload complete. Some changes may require server restart.");
args.Player.SendMessage(
"Configuration, Permissions, and Regions reload complete. Some changes may require server restart.");
}
private static void ServerPassword(CommandArgs args)
@ -1806,7 +1830,6 @@ namespace TShockAPI
private static void Settle(CommandArgs args)
{
if (Liquid.panicMode)
{
args.Player.SendMessage("Liquid is already settling!", Color.Red);
@ -1814,7 +1837,6 @@ namespace TShockAPI
}
Liquid.StartPanic();
TShock.Utils.Broadcast("Settling all liquids...");
}
private static void MaxSpawns(CommandArgs args)
@ -1949,7 +1971,8 @@ namespace TShockAPI
{
foreach (Region r in TShock.Regions.Regions)
{
args.Player.SendMessage(r.Name + ": P: " + r.DisableBuild + " X: " + r.Area.X + " Y: " + r.Area.Y + " W: " + r.Area.Width + " H: " + r.Area.Height);
args.Player.SendMessage(r.Name + ": P: " + r.DisableBuild + " X: " + r.Area.X + " Y: " + r.Area.Y + " W: " +
r.Area.Width + " H: " + r.Area.Height);
foreach (int s in r.AllowedIDs)
{
args.Player.SendMessage(r.Name + ": " + s);
@ -2002,7 +2025,8 @@ namespace TShockAPI
var width = Math.Abs(args.Player.TempPoints[0].X - args.Player.TempPoints[1].X);
var height = Math.Abs(args.Player.TempPoints[0].Y - args.Player.TempPoints[1].Y);
if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.UserAccountName, Main.worldID.ToString()))
if (TShock.Regions.AddRegion(x, y, width, height, regionName, args.Player.UserAccountName,
Main.worldID.ToString()))
{
args.Player.TempPoints[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero;
@ -2284,7 +2308,8 @@ namespace TShockAPI
break;
}
args.Player.SendMessage(r.Name + ": P: " + r.DisableBuild + " X: " + r.Area.X + " Y: " + r.Area.Y + " W: " + r.Area.Width + " H: " + r.Area.Height);
args.Player.SendMessage(r.Name + ": P: " + r.DisableBuild + " X: " + r.Area.X + " Y: " + r.Area.Y + " W: " +
r.Area.Width + " H: " + r.Area.Height);
foreach (int s in r.AllowedIDs)
{
var user = TShock.Users.GetUserByID(s);
@ -2345,12 +2370,14 @@ namespace TShockAPI
}
else
{
args.Player.SendMessage("Invalid syntax! Proper syntax: /region resize [regionname] [u/d/l/r] [amount]", Color.Red);
args.Player.SendMessage("Invalid syntax! Proper syntax: /region resize [regionname] [u/d/l/r] [amount]",
Color.Red);
}
}
else
{
args.Player.SendMessage("Invalid syntax! Proper syntax: /region resize [regionname] [u/d/l/r] [amount]1", Color.Red);
args.Player.SendMessage("Invalid syntax! Proper syntax: /region resize [regionname] [u/d/l/r] [amount]1",
Color.Red);
}
break;
}
@ -2358,7 +2385,8 @@ namespace TShockAPI
default:
{
args.Player.SendMessage("Avialable region commands:", Color.Green);
args.Player.SendMessage("/region set [1/2] /region define [name] /region protect [name] [true/false]", Color.Yellow);
args.Player.SendMessage("/region set [1/2] /region define [name] /region protect [name] [true/false]",
Color.Yellow);
args.Player.SendMessage("/region name (provides region name)", Color.Yellow);
args.Player.SendMessage("/region delete [name] /region clear (temporary region)", Color.Yellow);
args.Player.SendMessage("/region allow [name] [regionname]", Color.Yellow);
@ -2415,7 +2443,8 @@ namespace TShockAPI
private static void Playing(CommandArgs args)
{
args.Player.SendMessage(string.Format("Current players: {0}.", TShock.Utils.GetPlayers()), 255, 240, 20);
args.Player.SendMessage(string.Format("TShock: {0} ({1}): ({2}/{3})", TShock.VersionNum, TShock.VersionCodename, TShock.Utils.ActivePlayers(), TShock.Config.MaxSlots));
args.Player.SendMessage(string.Format("TShock: {0} ({1}): ({2}/{3})", TShock.VersionNum, TShock.VersionCodename,
TShock.Utils.ActivePlayers(), TShock.Config.MaxSlots));
}
private static void AuthToken(CommandArgs args)
@ -2555,7 +2584,6 @@ namespace TShockAPI
}
else
args.Player.SendMessage("You cannot mute this player.");
}
private static void Motd(CommandArgs args)
@ -2609,7 +2637,8 @@ namespace TShockAPI
args.Player.SendMessage("(Whisper To)" + "<" + args.Player.LastWhisper.Name + ">" + msg, Color.MediumPurple);
}
else
args.Player.SendMessage("You haven't previously received any whispers. Please use /whisper to whisper to other people.", Color.Red);
args.Player.SendMessage(
"You haven't previously received any whispers. Please use /whisper to whisper to other people.", Color.Red);
}
private static void Annoy(CommandArgs args)
@ -2694,7 +2723,8 @@ namespace TShockAPI
{
if (args.Parameters.Count < 1)
{
args.Player.SendMessage("Invalid syntax! Proper syntax: /item <item name/id> [item amount] [prefix id/name]", Color.Red);
args.Player.SendMessage("Invalid syntax! Proper syntax: /item <item name/id> [item amount] [prefix id/name]",
Color.Red);
return;
}
if (args.Parameters[0].Length == 0)
@ -2750,7 +2780,8 @@ namespace TShockAPI
{
if (args.Parameters.Count < 2)
{
args.Player.SendMessage("Invalid syntax! Proper syntax: /give <item type/id> <player> [item amount] [prefix id/name]", Color.Red);
args.Player.SendMessage(
"Invalid syntax! Proper syntax: /give <item type/id> <player> [item amount] [prefix id/name]", Color.Red);
return;
}
if (args.Parameters[0].Length == 0)
@ -2827,7 +2858,6 @@ namespace TShockAPI
public static void ClearItems(CommandArgs args)
{
int radius = 50;
if (args.Parameters.Count > 0)
{
@ -2841,14 +2871,20 @@ namespace TShockAPI
{
radius = Convert.ToInt32(args.Parameters[0]);
}
catch (Exception) { args.Player.SendMessage("Please either enter the keyword \"all\", or the block radius you wish to delete all items from.", Color.Red); return; }
catch (Exception)
{
args.Player.SendMessage(
"Please either enter the keyword \"all\", or the block radius you wish to delete all items from.", Color.Red);
return;
}
}
}
int count = 0;
for (int i = 0; i < 200; i++)
{
if ((Math.Sqrt(Math.Pow(Main.item[i].position.X - args.Player.X, 2) + Math.Pow(Main.item[i].position.Y - args.Player.Y, 2)) < radius * 16) && (Main.item[i].active))
if (
(Math.Sqrt(Math.Pow(Main.item[i].position.X - args.Player.X, 2) +
Math.Pow(Main.item[i].position.Y - args.Player.Y, 2)) < radius*16) && (Main.item[i].active))
{
Main.item[i].active = false;
NetMessage.SendData(0x15, -1, -1, "", i, 0f, 0f, 0f, 0);
@ -2856,7 +2892,6 @@ namespace TShockAPI
}
}
args.Player.SendMessage("All " + count + " items within a radius of " + radius + " have been deleted.");
}
private static void Heal(CommandArgs args)
@ -2940,7 +2975,8 @@ namespace TShockAPI
time = 60;
args.Player.SetBuff(id, time*60);
args.Player.SendMessage(string.Format("You have buffed yourself with {0}({1}) for {2} seconds!",
TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)), Color.Green);
TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)),
Color.Green);
}
else
args.Player.SendMessage("Invalid buff ID!", Color.Red);
@ -2991,9 +3027,11 @@ namespace TShockAPI
time = 60;
foundplr[0].SetBuff(id, time*60);
args.Player.SendMessage(string.Format("You have buffed {0} with {1}({2}) for {3} seconds!",
foundplr[0].Name, TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)), Color.Green);
foundplr[0].Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)), Color.Green);
foundplr[0].SendMessage(string.Format("{0} has buffed you with {1}({2}) for {3} seconds!",
args.Player.Name, TShock.Utils.GetBuffName(id), TShock.Utils.GetBuffDescription(id), (time)), Color.Green);
args.Player.Name, TShock.Utils.GetBuffName(id),
TShock.Utils.GetBuffDescription(id), (time)), Color.Green);
}
else
args.Player.SendMessage("Invalid buff ID!", Color.Red);

View file

@ -26,204 +26,174 @@ namespace TShockAPI
{
public class ConfigFile
{
[Description("The equation for calculating invasion size is 100 + (multiplier * (number of active players with greater than 200 health))")]
public int InvasionMultiplier = 1;
[Description("The default maximum mobs that will spawn per wave. Higher means more mobs in that wave.")]
public int DefaultMaximumSpawns = 5;
[Description("The delay between waves. Shorter values lead to less mobs.")]
public int DefaultSpawnRate = 600;
[Description("The port the server runs on.")]
public int ServerPort = 7777;
[Description("Enable or disable the whitelist based on IP addresses in whitelist.txt")]
public bool EnableWhitelist;
[Description("Enable the ability for invaison size to never decrease. Make sure to run /invade, and note that this adds 2 million+ goblins to the spawn que for the map.")]
public bool InfiniteInvasion;
[Description("Set the server pvp mode. Vaild types are, \"normal\", \"always\", \"disabled\"")]
public string PvPMode = "normal";
[Description("Prevents tiles from being placed within SpawnProtectionRadius of the default spawn.")]
public bool SpawnProtection = true;
[Description("Radius from spawn tile for SpawnProtection.")]
public int SpawnProtectionRadius = 10;
[Description("Max slots for the server. If you want people to be kicked with \"Server is full\" set this to how many players you want max and then set Terraria max players to 2 higher.")]
public int MaxSlots = 8;
[Description("Global protection agent for any block distance based anti-grief check.")]
public bool RangeChecks = true;
[Description("Disables any building; placing of blocks")]
public bool DisableBuild;
[Description("#.#.#. = Red/Blue/Green - RGB Colors for the Admin Chat Color. Max value: 255")]
public float[] SuperAdminChatRGB = { 255, 0, 0 };
[Description("Super admin group chat prefix")]
public string SuperAdminChatPrefix = "(Admin) ";
[Description("Super admin group chat suffix")]
public string SuperAdminChatSuffix = "";
[Description("Backup frequency in minutes. So, a value of 60 = 60 minutes. Backups are stored in the \\tshock\\backups folder.")]
public int BackupInterval;
[Description("How long backups are kept in minutes. 2880 = 2 days.")]
public int BackupKeepFor = 60;
[Description(
"The equation for calculating invasion size is 100 + (multiplier * (number of active players with greater than 200 health))"
)] public int InvasionMultiplier = 1;
[Description("Remembers where a player left off. It works by remembering the IP, NOT the character. \neg. When you try to disconnect, and reconnect to be automatically placed at spawn, you'll be at your last location. Note: Won't save after server restarts.")]
public bool RememberLeavePos;
[Description("Hardcore players ONLY. This means softcore players cannot join.")]
public bool HardcoreOnly;
[Description("Mediumcore players ONLY. This means softcore players cannot join.")]
public bool MediumcoreOnly;
[Description("Kicks a Hardcore player on death.")]
public bool KickOnMediumcoreDeath;
[Description("Bans a Hardcore player on death.")]
public bool BanOnMediumcoreDeath;
[Description("The default maximum mobs that will spawn per wave. Higher means more mobs in that wave.")] public int
DefaultMaximumSpawns = 5;
[Description("Enable/Disable Terrarias built in auto save")]
public bool AutoSave = true;
[Description("The delay between waves. Shorter values lead to less mobs.")] public int DefaultSpawnRate = 600;
[Description("The port the server runs on.")] public int ServerPort = 7777;
[Description("Enable or disable the whitelist based on IP addresses in whitelist.txt")] public bool EnableWhitelist;
[Description("Number of failed login attempts before kicking the player.")]
public int MaximumLoginAttempts = 3;
[Description(
"Enable the ability for invaison size to never decrease. Make sure to run /invade, and note that this adds 2 million+ goblins to the spawn que for the map."
)] public bool InfiniteInvasion;
[Description("Not implemented")]
public string RconPassword = "";
[Description("Not implemented")]
public int RconPort = 7777;
[Description("Set the server pvp mode. Vaild types are, \"normal\", \"always\", \"disabled\"")] public string PvPMode
= "normal";
[Description("Not implemented")]
public string ServerName = "";
[Description("Not implemented")]
public string MasterServer = "127.0.0.1";
[Description("Prevents tiles from being placed within SpawnProtectionRadius of the default spawn.")] public bool
SpawnProtection = true;
[Description("Valid types are \"sqlite\" and \"mysql\"")]
public string StorageType = "sqlite";
[Description("Radius from spawn tile for SpawnProtection.")] public int SpawnProtectionRadius = 10;
[Description("The MySQL Hostname and port to direct connections to")]
public string MySqlHost = "localhost:3306";
[Description("Database name to connect to")]
public string MySqlDbName = "";
[Description("Database username to connect with")]
public string MySqlUsername = "";
[Description("Database password to connect with")]
public string MySqlPassword = "";
[Description(
"Max slots for the server. If you want people to be kicked with \"Server is full\" set this to how many players you want max and then set Terraria max players to 2 higher."
)] public int MaxSlots = 8;
[Description("Bans a Mediumcore player on death.")]
public string MediumcoreBanReason = "Death results in a ban";
[Description("Kicks a Mediumcore player on death.")]
public string MediumcoreKickReason = "Death results in a kick";
[Description("Global protection agent for any block distance based anti-grief check.")] public bool RangeChecks = true;
[Description("Disables any building; placing of blocks")] public bool DisableBuild;
[Description("Enables DNS resolution of incoming connections with GetGroupForIPExpensive.")]
public bool EnableDNSHostResolution;
[Description("#.#.#. = Red/Blue/Green - RGB Colors for the Admin Chat Color. Max value: 255")] public float[]
SuperAdminChatRGB = {255, 0, 0};
[Description("Enables kicking of banned users by matching their IP Address")]
public bool EnableIPBans = true;
[Description("Super admin group chat prefix")] public string SuperAdminChatPrefix = "(Admin) ";
[Description("Super admin group chat suffix")] public string SuperAdminChatSuffix = "";
[Description("Enables kicking of banned users by matching their Character Name")]
public bool EnableBanOnUsernames;
[Description(
"Backup frequency in minutes. So, a value of 60 = 60 minutes. Backups are stored in the \\tshock\\backups folder.")] public int BackupInterval;
[Description("Drops excessive sync packets")]
public bool EnableAntiLag = true;
[Description("How long backups are kept in minutes. 2880 = 2 days.")] public int BackupKeepFor = 60;
[Description("Selects the default group name to place new registrants under")]
public string DefaultRegistrationGroupName = "default";
[Description(
"Remembers where a player left off. It works by remembering the IP, NOT the character. \neg. When you try to disconnect, and reconnect to be automatically placed at spawn, you'll be at your last location. Note: Won't save after server restarts."
)] public bool RememberLeavePos;
[Description("Selects the default group name to place non registered users under")]
public string DefaultGuestGroupName = "guest";
[Description("Hardcore players ONLY. This means softcore players cannot join.")] public bool HardcoreOnly;
[Description("Mediumcore players ONLY. This means softcore players cannot join.")] public bool MediumcoreOnly;
[Description("Kicks a Hardcore player on death.")] public bool KickOnMediumcoreDeath;
[Description("Bans a Hardcore player on death.")] public bool BanOnMediumcoreDeath;
[Description("Force-Disable printing logs to players with the log permission")]
public bool DisableSpewLogs = true;
[Description("Enable/Disable Terrarias built in auto save")] public bool AutoSave = true;
[Description("Valid types are \"sha512\", \"sha256\", \"md5\", append with \"-xp\" for the xp supported algorithms")]
public string HashAlgorithm = "sha512";
[Description("Number of failed login attempts before kicking the player.")] public int MaximumLoginAttempts = 3;
[Description("Buffers up the packets and sends them out at the end of each frame")]
public bool BufferPackets = true;
[Description("Not implemented")] public string RconPassword = "";
[Description("Not implemented")] public int RconPort = 7777;
[Description("String that is used when kicking people when the server is full.")]
public string ServerFullReason = "Server is full";
[Description("Not implemented")] public string ServerName = "";
[Description("Not implemented")] public string MasterServer = "127.0.0.1";
[Description("String that is used when kicking people when the server is full with no reserved slots.")]
public string ServerFullNoReservedReason = "Server is full. No reserved slots open.";
[Description("Valid types are \"sqlite\" and \"mysql\"")] public string StorageType = "sqlite";
[Description("This will save the world if Terraria crashes from an unhandled exception.")]
public bool SaveWorldOnCrash = true;
[Description("The MySQL Hostname and port to direct connections to")] public string MySqlHost = "localhost:3306";
[Description("Database name to connect to")] public string MySqlDbName = "";
[Description("Database username to connect with")] public string MySqlUsername = "";
[Description("Database password to connect with")] public string MySqlPassword = "";
[Description("This will announce a player's location on join")]
public bool EnableGeoIP;
[Description("Bans a Mediumcore player on death.")] public string MediumcoreBanReason = "Death results in a ban";
[Description("Kicks a Mediumcore player on death.")] public string MediumcoreKickReason = "Death results in a kick";
[Description("This will turn on a token requirement for the /status API endpoint.")]
public bool EnableTokenEndpointAuthentication;
[Description("Enables DNS resolution of incoming connections with GetGroupForIPExpensive.")] public bool
EnableDNSHostResolution;
[Description("This is used when the API endpoint /status is queried.")]
public string ServerNickname = "TShock Server";
[Description("Enables kicking of banned users by matching their IP Address")] public bool EnableIPBans = true;
[Description("Enable/Disable the rest api.")]
public bool RestApiEnabled;
[Description("Enables kicking of banned users by matching their Character Name")] public bool EnableBanOnUsernames;
[Description("This is the port which the rest api will listen on.")]
public int RestApiPort = 7878;
[Description("Drops excessive sync packets")] public bool EnableAntiLag = true;
[Description("Disable tombstones for all players.")]
public bool DisableTombstones = true;
[Description("Selects the default group name to place new registrants under")] public string
DefaultRegistrationGroupName = "default";
[Description("Displays a player's IP on join to everyone who has the log permission")]
public bool DisplayIPToAdmins;
[Description("Selects the default group name to place non registered users under")] public string
DefaultGuestGroupName = "guest";
[Description("Some tiles are 'fixed' by not letting TShock handle them. Disabling this may break certain asthetic tiles.")]
public bool EnableInsecureTileFixes = true;
[Description("Force-Disable printing logs to players with the log permission")] public bool DisableSpewLogs = true;
[Description("Kicks users using a proxy as identified with the GeoIP database")]
public bool KickProxyUsers = true;
[Description("Valid types are \"sha512\", \"sha256\", \"md5\", append with \"-xp\" for the xp supported algorithms")] public string HashAlgorithm = "sha512";
[Description("Disables hardmode, can't never be activated. Overrides /starthardmode")]
public bool DisableHardmode;
[Description("Buffers up the packets and sends them out at the end of each frame")] public bool BufferPackets = true;
[Description("Disables Dungeon Guardian from being spawned by player packets, this will instead force a respawn")]
public bool DisableDungeonGuardian;
[Description("String that is used when kicking people when the server is full.")] public string ServerFullReason =
"Server is full";
[Description("Enable Server Side Inventory checks, EXPERIMENTAL")]
public bool ServerSideInventory;
[Description("String that is used when kicking people when the server is full with no reserved slots.")] public string
ServerFullNoReservedReason = "Server is full. No reserved slots open.";
[Description("Disables reporting of playercount to the stat system.")]
public bool DisablePlayerCountReporting;
[Description("This will save the world if Terraria crashes from an unhandled exception.")] public bool
SaveWorldOnCrash = true;
[Description("Disables clown bomb projectiles from spawning")]
public bool DisableClownBombs;
[Description("This will announce a player's location on join")] public bool EnableGeoIP;
[Description("Disables snow ball projectiles from spawning")]
public bool DisableSnowBalls;
[Description("This will turn on a token requirement for the /status API endpoint.")] public bool
EnableTokenEndpointAuthentication;
[Description("Change ingame chat format, {0} = Group Name, {1} = Group Prefix, {2} = Player Name, {3} = Group Suffix, {4} = Chat Message")]
public string ChatFormat = "{1}{2}{3}: {4}";
[Description("This is used when the API endpoint /status is queried.")] public string ServerNickname = "TShock Server";
[Description("Force the world time to be normal, day, or night")]
public string ForceTime = "normal";
[Description("Enable/Disable the rest api.")] public bool RestApiEnabled;
[Description("Disable/Revert a player if they exceed this number of tile kills within 1 second.")]
public int TileKillThreshold = 60;
[Description("This is the port which the rest api will listen on.")] public int RestApiPort = 7878;
[Description("Disable/Revert a player if they exceed this number of tile places within 1 second.")]
public int TilePlaceThreshold = 20;
[Description("Disable tombstones for all players.")] public bool DisableTombstones = true;
[Description("Disable a player if they exceed this number of liquid sets within 1 second.")]
public int TileLiquidThreshold = 15;
[Description("Displays a player's IP on join to everyone who has the log permission")] public bool DisplayIPToAdmins;
[Description("Disable a player if they exceed this number of projectile new within 1 second.")]
public int ProjectileThreshold = 50;
[Description(
"Some tiles are 'fixed' by not letting TShock handle them. Disabling this may break certain asthetic tiles.")] public
bool EnableInsecureTileFixes = true;
[Description("Require all players to register or login before being allowed to play.")]
public bool RequireLogin;
[Description("Kicks users using a proxy as identified with the GeoIP database")] public bool KickProxyUsers = true;
[Description("Disables Invisibility potions from being used in PvP (Note, they can use them on the client, but the effect isn't sent to the rest of the server)")]
public bool DisableInvisPvP;
[Description("Disables hardmode, can't never be activated. Overrides /starthardmode")] public bool DisableHardmode;
[Description("The maximum distance players disabled for various reasons can move from")]
public int MaxRangeForDisabled = 10;
[Description("Disables Dungeon Guardian from being spawned by player packets, this will instead force a respawn")] public bool DisableDungeonGuardian;
[Description("Server password required to join server")]
public string ServerPassword = "";
[Description("Enable Server Side Inventory checks, EXPERIMENTAL")] public bool ServerSideInventory;
[Description("Protect chests with region and build permissions")]
public bool RegionProtectChests;
[Description("Disables reporting of playercount to the stat system.")] public bool DisablePlayerCountReporting;
[Description("Disable users from being able to login with account password when joining")]
public bool DisableLoginBeforeJoin;
[Description("Disables clown bomb projectiles from spawning")] public bool DisableClownBombs;
[Description("Allows users to register any username with /register")]
public bool AllowRegisterAnyUsername;
[Description("Disables snow ball projectiles from spawning")] public bool DisableSnowBalls;
[Description(
"Change ingame chat format, {0} = Group Name, {1} = Group Prefix, {2} = Player Name, {3} = Group Suffix, {4} = Chat Message"
)] public string ChatFormat = "{1}{2}{3}: {4}";
[Description("Force the world time to be normal, day, or night")] public string ForceTime = "normal";
[Description("Disable/Revert a player if they exceed this number of tile kills within 1 second.")] public int
TileKillThreshold = 60;
[Description("Disable/Revert a player if they exceed this number of tile places within 1 second.")] public int
TilePlaceThreshold = 20;
[Description("Disable a player if they exceed this number of liquid sets within 1 second.")] public int
TileLiquidThreshold = 15;
[Description("Disable a player if they exceed this number of projectile new within 1 second.")] public int
ProjectileThreshold = 50;
[Description("Require all players to register or login before being allowed to play.")] public bool RequireLogin;
[Description(
"Disables Invisibility potions from being used in PvP (Note, they can use them on the client, but the effect isn't sent to the rest of the server)"
)] public bool DisableInvisPvP;
[Description("The maximum distance players disabled for various reasons can move from")] public int
MaxRangeForDisabled = 10;
[Description("Server password required to join server")] public string ServerPassword = "";
[Description("Protect chests with region and build permissions")] public bool RegionProtectChests;
[Description("Disable users from being able to login with account password when joining")] public bool
DisableLoginBeforeJoin;
[Description("Allows users to register any username with /register")] public bool AllowRegisterAnyUsername;
public static ConfigFile Read(string path)
{
@ -266,7 +236,7 @@ namespace TShockAPI
public static Action<ConfigFile> ConfigRead;
static void DumpDescriptions()
private static void DumpDescriptions()
{
var sb = new StringBuilder();
var defaults = new ConfigFile();
@ -279,7 +249,8 @@ namespace TShockAPI
var name = field.Name;
var type = field.FieldType.Name;
var descattr = field.GetCustomAttributes(false).FirstOrDefault(o => o is DescriptionAttribute) as DescriptionAttribute;
var descattr =
field.GetCustomAttributes(false).FirstOrDefault(o => o is DescriptionAttribute) as DescriptionAttribute;
var desc = descattr != null && !string.IsNullOrWhiteSpace(descattr.Description) ? descattr.Description : "None";
var def = field.GetValue(defaults);

View file

@ -36,7 +36,10 @@ namespace TShockAPI.DB
new SqlColumn("Name", MySqlDbType.Text),
new SqlColumn("Reason", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "bans.txt");
@ -98,7 +101,6 @@ namespace TShockAPI.DB
{
if (reader.Read())
return new Ban(reader.Get<string>("IP"), reader.Get<string>("Name"), reader.Get<string>("Reason"));
}
}
catch (Exception ex)
@ -133,6 +135,7 @@ namespace TShockAPI.DB
}
return false;
}
public bool ClearBans()
{
try

View file

@ -25,14 +25,18 @@ namespace TShockAPI.DB
new SqlColumn("Prefix", MySqlDbType.Text),
new SqlColumn("Suffix", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
//Add default groups
AddGroup("guest", "canbuild,canregister,canlogin,canpartychat,cantalkinthird");
AddGroup("default", "guest", "warp,canchangepassword");
AddGroup("newadmin", "default", "kick,editspawn,reservedslot");
AddGroup("admin", "newadmin", "ban,unban,whitelist,causeevents,spawnboss,spawnmob,managewarp,time,tp,pvpfun,kill,logs,immunetokick,tphere");
AddGroup("admin", "newadmin",
"ban,unban,whitelist,causeevents,spawnboss,spawnmob,managewarp,time,tp,pvpfun,kill,logs,immunetokick,tphere");
AddGroup("trustedadmin", "admin", "maintenance,cfg,butcher,item,heal,immunetoban,usebanneditem,manageusers");
AddGroup("vip", "default", "reservedslot");
@ -63,7 +67,6 @@ namespace TShockAPI.DB
query = "INSERT IGNORE INTO GroupList SET GroupName=@0, Commands=@1;";
db.Query(query, info[0].Trim(), comms);
}
}
}
@ -75,7 +78,6 @@ namespace TShockAPI.DB
File.Delete(file2);
File.Move(file, file2);
}
}
@ -114,9 +116,9 @@ namespace TShockAPI.DB
group.Parent = parent;
}
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO GroupList (GroupName, Parent, Commands, ChatColor) VALUES (@0, @1, @2, @3);" :
"INSERT IGNORE INTO GroupList SET GroupName=@0, Parent=@1, Commands=@2, ChatColor=@3";
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
? "INSERT OR IGNORE INTO GroupList (GroupName, Parent, Commands, ChatColor) VALUES (@0, @1, @2, @3);"
: "INSERT IGNORE INTO GroupList SET GroupName=@0, Parent=@1, Commands=@2, ChatColor=@3";
if (database.Query(query, name, parentname, permissions, chatcolor) == 1)
message = "Group " + name + " has been created successfully.";
@ -124,10 +126,12 @@ namespace TShockAPI.DB
return message;
}
public String AddGroup(String name, String permissions)
{
return AddGroup(name, "", permissions, "255,255,255");
}
public String AddGroup(String name, string parent, String permissions)
{
return AddGroup(name, parent, permissions, "255,255,255");

View file

@ -22,10 +22,17 @@ namespace TShockAPI.DB
{
public string CreateTable(SqlTable table)
{
var columns = table.Columns.Select(c => "'{0}' {1} {2} {3} {4}".SFormat(c.Name, DbTypeToString(c.Type, c.Length), c.Primary ? "PRIMARY KEY" : "", c.AutoIncrement ? "AUTOINCREMENT" : "", c.NotNull ? "NOT NULL" : "", c.Unique ? "UNIQUE" : ""));
var columns =
table.Columns.Select(
c =>
"'{0}' {1} {2} {3} {4}".SFormat(c.Name, DbTypeToString(c.Type, c.Length), c.Primary ? "PRIMARY KEY" : "",
c.AutoIncrement ? "AUTOINCREMENT" : "", c.NotNull ? "NOT NULL" : "",
c.Unique ? "UNIQUE" : ""));
return "CREATE TABLE '{0}' ({1})".SFormat(table.Name, string.Join(", ", columns));
}
static Random rand = new Random();
private static Random rand = new Random();
/// <summary>
/// Alter a table from source to destination
/// </summary>
@ -39,7 +46,13 @@ namespace TShockAPI.DB
var create = CreateTable(to);
//combine all columns in the 'from' variable excluding ones that aren't in the 'to' variable.
//exclude the ones that aren't in 'to' variable because if the column is deleted, why try to import the data?
var insert = "INSERT INTO '{0}' ({1}) SELECT {1} FROM {2}_{0}".SFormat(from.Name, string.Join(", ", from.Columns.Where(c => to.Columns.Any(c2 => c2.Name == c.Name)).Select(c => c.Name)), rstr);
var insert = "INSERT INTO '{0}' ({1}) SELECT {1} FROM {2}_{0}".SFormat(from.Name,
string.Join(", ",
from.Columns.Where(
c =>
to.Columns.Any(
c2 => c2.Name == c.Name)).Select
(c => c.Name)), rstr);
var drop = "DROP TABLE '{0}_{1}'".SFormat(rstr, from.Name);
return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop);
/*
@ -51,6 +64,7 @@ namespace TShockAPI.DB
* Twitchy - Oh. I get it!
*/
}
public string DeleteRow(string table, List<SqlValue> wheres)
{
var sbwheres = new StringBuilder();
@ -67,6 +81,7 @@ namespace TShockAPI.DB
else
return "DELETE FROM '{0}'".SFormat(table, sbwheres.ToString());
}
public string UpdateValue(string table, List<SqlValue> values, List<SqlValue> wheres)
{
var sbvalues = new StringBuilder();
@ -93,6 +108,7 @@ namespace TShockAPI.DB
else
return "UPDATE '{0}' SET {1}".SFormat(table, sbvalues.ToString());
}
public string InsertValues(string table, List<SqlValue> values)
{
var sbnames = new StringBuilder();
@ -117,6 +133,7 @@ namespace TShockAPI.DB
}
return "INSERT INTO '{0}' ({1}) VALUES ({2})".SFormat(table, sbnames.ToString(), sbvalues.ToString());
}
public string ReadColumn(string table, List<SqlValue> wheres)
{
var sbwheres = new StringBuilder();
@ -136,7 +153,7 @@ namespace TShockAPI.DB
return "SELECT * FROM {0}".SFormat(table);
}
static readonly Dictionary<MySqlDbType, string> TypesAsStrings = new Dictionary<MySqlDbType, string>
private static readonly Dictionary<MySqlDbType, string> TypesAsStrings = new Dictionary<MySqlDbType, string>
{
{MySqlDbType.VarChar, "TEXT"},
{MySqlDbType.String, "TEXT"},
@ -146,6 +163,7 @@ namespace TShockAPI.DB
{MySqlDbType.LongText, "TEXT"},
{MySqlDbType.Int32, "INTEGER"},
};
public string DbTypeToString(MySqlDbType type, int? length)
{
string ret;
@ -154,15 +172,25 @@ namespace TShockAPI.DB
throw new NotImplementedException(Enum.GetName(typeof (MySqlDbType), type));
}
}
public class MysqlQueryCreator : IQueryBuilder
{
public string CreateTable(SqlTable table)
{
var columns = table.Columns.Select(c => "{0} {1} {2} {3}".SFormat(c.Name, DbTypeToString(c.Type, c.Length), c.Primary ? "PRIMARY KEY" : "", c.AutoIncrement ? "AUTO_INCREMENT" : "", c.NotNull ? "NOT NULL" : ""));
var columns =
table.Columns.Select(
c =>
"{0} {1} {2} {3}".SFormat(c.Name, DbTypeToString(c.Type, c.Length), c.Primary ? "PRIMARY KEY" : "",
c.AutoIncrement ? "AUTO_INCREMENT" : "", c.NotNull ? "NOT NULL" : ""));
var uniques = table.Columns.Where(c => c.Unique).Select(c => c.Name);
return "CREATE TABLE {0} ({1} {2})".SFormat(table.Name, string.Join(", ", columns), uniques.Count() > 0 ? ", UNIQUE({0})".SFormat(string.Join(", ", uniques)) : "");
return "CREATE TABLE {0} ({1} {2})".SFormat(table.Name, string.Join(", ", columns),
uniques.Count() > 0
? ", UNIQUE({0})".SFormat(string.Join(", ", uniques))
: "");
}
static Random rand = new Random();
private static Random rand = new Random();
/// <summary>
/// Alter a table from source to destination
/// </summary>
@ -176,10 +204,17 @@ namespace TShockAPI.DB
var create = CreateTable(to);
//combine all columns in the 'from' variable excluding ones that aren't in the 'to' variable.
//exclude the ones that aren't in 'to' variable because if the column is deleted, why try to import the data?
var insert = "INSERT INTO {0} ({1}) SELECT {1} FROM {2}_{0}".SFormat(from.Name, string.Join(", ", from.Columns.Where(c => to.Columns.Any(c2 => c2.Name == c.Name)).Select(c => c.Name)), rstr);
var insert = "INSERT INTO {0} ({1}) SELECT {1} FROM {2}_{0}".SFormat(from.Name,
string.Join(", ",
from.Columns.Where(
c =>
to.Columns.Any(
c2 => c2.Name == c.Name)).Select(
c => c.Name)), rstr);
var drop = "DROP TABLE {0}_{1}".SFormat(rstr, from.Name);
return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop);
}
public string DeleteRow(string table, List<SqlValue> wheres)
{
var sbwheres = new StringBuilder();
@ -196,6 +231,7 @@ namespace TShockAPI.DB
else
return "DELETE FROM {0}".SFormat(table, sbwheres.ToString());
}
public string UpdateValue(string table, List<SqlValue> values, List<SqlValue> wheres)
{
var sbvalues = new StringBuilder();
@ -222,6 +258,7 @@ namespace TShockAPI.DB
else
return "UPDATE {0} SET {1}".SFormat(table, sbvalues.ToString());
}
public string InsertValues(string table, List<SqlValue> values)
{
var sbnames = new StringBuilder();
@ -247,6 +284,7 @@ namespace TShockAPI.DB
return "INSERT INTO {0} ({1}) VALUES ({2})".SFormat(table, sbnames.ToString(), sbvalues.ToString());
}
public string ReadColumn(string table, List<SqlValue> wheres)
{
var sbwheres = new StringBuilder();
@ -266,7 +304,7 @@ namespace TShockAPI.DB
return "SELECT * FROM {0}".SFormat(table);
}
static readonly Dictionary<MySqlDbType, string> TypesAsStrings = new Dictionary<MySqlDbType, string>
private static readonly Dictionary<MySqlDbType, string> TypesAsStrings = new Dictionary<MySqlDbType, string>
{
{MySqlDbType.VarChar, "VARCHAR"},
{MySqlDbType.String, "CHAR"},
@ -276,6 +314,7 @@ namespace TShockAPI.DB
{MySqlDbType.LongText, "LONGTEXT"},
{MySqlDbType.Int32, "INT"},
};
public string DbTypeToString(MySqlDbType type, int? length)
{
string ret;

View file

@ -36,7 +36,10 @@ namespace TShockAPI.DB
new SqlColumn("MaxMana", MySqlDbType.Int32),
new SqlColumn("Inventory", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
}
@ -76,7 +79,8 @@ namespace TShockAPI.DB
{
try
{
database.Query("INSERT INTO Inventory (Account, MaxHealth, Inventory) VALUES (@0, @1, @2);", player.UserID, playerData.maxHealth, NetItem.ToString(playerData.inventory));
database.Query("INSERT INTO Inventory (Account, MaxHealth, Inventory) VALUES (@0, @1, @2);", player.UserID,
playerData.maxHealth, NetItem.ToString(playerData.inventory));
return true;
}
catch (Exception ex)
@ -88,7 +92,8 @@ namespace TShockAPI.DB
{
try
{
database.Query("UPDATE Inventory SET MaxHealth = @0, Inventory = @1 WHERE Account = @2;", playerData.maxHealth, NetItem.ToString(playerData.inventory), player.UserID);
database.Query("UPDATE Inventory SET MaxHealth = @0, Inventory = @1 WHERE Account = @2;", playerData.maxHealth,
NetItem.ToString(playerData.inventory), player.UserID);
return true;
}
catch (Exception ex)

View file

@ -20,7 +20,10 @@ namespace TShockAPI.DB
new SqlColumn("ItemName", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("AllowedGroups", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "itembans.txt");
@ -33,10 +36,9 @@ namespace TShockAPI.DB
{
if (!line.Equals("") && !line.Substring(0, 1).Equals("#"))
{
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO 'ItemBans' (ItemName, AllowedGroups) VALUES (@0, @1);" :
"INSERT IGNORE INTO ItemBans SET ItemName=@0,AllowedGroups=@1 ;";
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
? "INSERT OR IGNORE INTO 'ItemBans' (ItemName, AllowedGroups) VALUES (@0, @1);"
: "INSERT IGNORE INTO ItemBans SET ItemName=@0,AllowedGroups=@1 ;";
int id = 0;
int.TryParse(line, out id);
@ -77,7 +79,8 @@ namespace TShockAPI.DB
{
try
{
database.Query("INSERT INTO ItemBans (ItemName, AllowedGroups) VALUES (@0, @1);", TShock.Utils.GetItemByName(itemname)[0].name, "");
database.Query("INSERT INTO ItemBans (ItemName, AllowedGroups) VALUES (@0, @1);",
TShock.Utils.GetItemByName(itemname)[0].name, "");
if (!ItemIsBanned(itemname, null))
ItemBans.Add(new ItemBan(itemname));
}
@ -197,7 +200,8 @@ namespace TShockAPI.DB
{
if (ply == null)
return false;
return AllowedGroups.Contains(ply.Group.Name); // could add in the other permissions in this class instead of a giant if switch.
return AllowedGroups.Contains(ply.Group.Name);
// could add in the other permissions in this class instead of a giant if switch.
}
public void SetAllowedGroups(String groups)
@ -221,5 +225,4 @@ namespace TShockAPI.DB
return AllowedGroups.Remove(groupName);
}
}
}

View file

@ -48,14 +48,15 @@ namespace TShockAPI.DB
new SqlColumn("Protected", MySqlDbType.Int32),
new SqlColumn("Groups", MySqlDbType.Text),
new SqlColumn("Owner", MySqlDbType.VarChar, 50)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
ImportOld();
ReloadAllRegions();
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
@ -130,14 +131,14 @@ namespace TShockAPI.DB
}
region.Area = rect;
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO Regions VALUES (@0, @1, @2, @3, @4, @5, @6, @7);" :
"INSERT IGNORE INTO Regions SET X1=@0, Y1=@1, height=@2, width=@3, RegionName=@4, WorldID=@5, UserIds=@6, Protected=@7;";
database.Query(query, region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Name, region.WorldID, "", region.DisableBuild);
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
? "INSERT OR IGNORE INTO Regions VALUES (@0, @1, @2, @3, @4, @5, @6, @7);"
: "INSERT IGNORE INTO Regions SET X1=@0, Y1=@1, height=@2, width=@3, RegionName=@4, WorldID=@5, UserIds=@6, Protected=@7;";
database.Query(query, region.Area.X, region.Area.Y, region.Area.Width, region.Area.Height, region.Name,
region.WorldID, "", region.DisableBuild);
//Todo: What should this be? We don't really have a way to go from ips to userids
/*string.Join(",", region.AllowedIDs)*/
}
}
@ -220,7 +221,6 @@ namespace TShockAPI.DB
public void ReloadForUnitTest(String n)
{
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", n))
{
Regions.Clear();
@ -263,7 +263,6 @@ namespace TShockAPI.DB
Regions.Add(r);
}
}
}
public bool AddRegion(int tx, int ty, int width, int height, string regionname, string owner, string worldid)
@ -274,7 +273,8 @@ namespace TShockAPI.DB
}
try
{
database.Query("INSERT INTO Regions (X1, Y1, width, height, RegionName, WorldID, UserIds, Protected, Groups, Owner) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9);",
database.Query(
"INSERT INTO Regions (X1, Y1, width, height, RegionName, WorldID, UserIds, Protected, Groups, Owner) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9);",
tx, ty, width, height, regionname, worldid, "", 1, "", owner);
Regions.Add(new Region(new Rectangle(tx, ty, width, height), regionname, owner, true, worldid));
return true;
@ -306,7 +306,8 @@ namespace TShockAPI.DB
{
try
{
database.Query("UPDATE Regions SET Protected=@0 WHERE RegionName=@1 AND WorldID=@2", state ? 1 : 0, name, Main.worldID.ToString());
database.Query("UPDATE Regions SET Protected=@0 WHERE RegionName=@1 AND WorldID=@2", state ? 1 : 0, name,
Main.worldID.ToString());
var region = GetRegionByName(name);
if (region != null)
region.DisableBuild = state;
@ -397,7 +398,9 @@ namespace TShockAPI.DB
int width = 0;
try
{
using (var reader = database.QueryReader("SELECT X1, Y1, height, width FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName, Main.worldID.ToString()))
using (
var reader = database.QueryReader("SELECT X1, Y1, height, width FROM Regions WHERE RegionName=@0 AND WorldID=@1",
regionName, Main.worldID.ToString()))
{
if (reader.Read())
X = reader.Get<int>("X1");
@ -436,7 +439,10 @@ namespace TShockAPI.DB
Y -= addAmount;
height += addAmount;
}
int q = database.Query("UPDATE Regions SET X1 = @0, Y1 = @1, width = @2, height = @3 WHERE RegionName = @4 AND WorldID=@5", X, Y, width, height, regionName, Main.worldID.ToString());
int q =
database.Query(
"UPDATE Regions SET X1 = @0, Y1 = @1, width = @2, height = @3 WHERE RegionName = @4 AND WorldID=@5", X, Y, width,
height, regionName, Main.worldID.ToString());
if (q > 0)
return true;
}
@ -461,12 +467,15 @@ namespace TShockAPI.DB
}
return false;
}
public bool AddNewUser(string regionName, String userName)
{
try
{
string MergedIDs = string.Empty;
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName, Main.worldID.ToString()))
using (
var reader = database.QueryReader("SELECT * FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName,
Main.worldID.ToString()))
{
if (reader.Read())
MergedIDs = reader.Get<string>("UserIds");
@ -548,7 +557,9 @@ namespace TShockAPI.DB
public bool AllowGroup(string regionName, string groups)
{
string groupsNew = "";
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName, Main.worldID.ToString()))
using (
var reader = database.QueryReader("SELECT * FROM Regions WHERE RegionName=@0 AND WorldID=@1", regionName,
Main.worldID.ToString()))
{
if (reader.Read())
groupsNew = reader.Get<string>("Groups");
@ -607,7 +618,6 @@ namespace TShockAPI.DB
Owner = owner;
DisableBuild = disablebuild;
WorldID = RegionWorldIDz;
}
public Region()
@ -645,7 +655,8 @@ namespace TShockAPI.DB
return true;
}
return AllowedIDs.Contains(ply.UserID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.UserAccountName || ply.Group.HasPermission("manageregion");
return AllowedIDs.Contains(ply.UserID) || AllowedGroups.Contains(ply.Group.Name) || Owner == ply.UserAccountName ||
ply.Group.HasPermission("manageregion");
}
public void setAllowedIDs(String ids)

View file

@ -38,7 +38,10 @@ namespace TShockAPI.DB
new SqlColumn("Y", MySqlDbType.Int32),
new SqlColumn("WorldID", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
}
@ -68,7 +71,8 @@ namespace TShockAPI.DB
{
try
{
database.Query("INSERT INTO RememberedPos (Name, IP, X, Y, WorldID) VALUES (@0, @1, @2, @3, @4);", name, IP, X, Y + 3, Main.worldID.ToString());
database.Query("INSERT INTO RememberedPos (Name, IP, X, Y, WorldID) VALUES (@0, @1, @2, @3, @4);", name, IP, X,
Y + 3, Main.worldID.ToString());
}
catch (Exception ex)
{
@ -79,7 +83,8 @@ namespace TShockAPI.DB
{
try
{
database.Query("UPDATE RememberedPos SET X = @0, Y = @1 WHERE Name = @2 AND IP = @3 AND WorldID = @4;", X, Y + 3, name, IP, Main.worldID.ToString());
database.Query("UPDATE RememberedPos SET X = @0, Y = @1 WHERE Name = @2 AND IP = @3 AND WorldID = @4;", X, Y + 3,
name, IP, Main.worldID.ToString());
}
catch (Exception ex)
{

View file

@ -25,6 +25,7 @@ namespace TShockAPI.DB
: this(name, type, null)
{
}
public SqlColumn(string name, MySqlDbType type, int? length)
{
Name = name;

View file

@ -10,10 +10,12 @@ namespace TShockAPI.DB
{
public List<SqlColumn> Columns { get; protected set; }
public string Name { get; protected set; }
public SqlTable(string name, params SqlColumn[] columns)
: this(name, new List<SqlColumn>(columns))
{
}
public SqlTable(string name, List<SqlColumn> columns)
{
Name = name;
@ -23,8 +25,9 @@ namespace TShockAPI.DB
public class SqlTableCreator
{
IDbConnection database;
IQueryBuilder creator;
private IDbConnection database;
private IQueryBuilder creator;
public SqlTableCreator(IDbConnection db, IQueryBuilder provider)
{
database = db;
@ -62,7 +65,11 @@ namespace TShockAPI.DB
}
else if (name == SqlType.Mysql)
{
using (var reader = database.QueryReader("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME=@0 AND TABLE_SCHEMA=@1", table.Name, database.Database))
using (
var reader =
database.QueryReader(
"SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME=@0 AND TABLE_SCHEMA=@1", table.Name,
database.Database))
{
while (reader.Read())
ret.Add(reader.Get<string>("COLUMN_NAME"));

View file

@ -17,8 +17,8 @@ namespace TShockAPI.DB
public class SqlTableEditor
{
IDbConnection database;
IQueryBuilder creator;
private IDbConnection database;
private IQueryBuilder creator;
public SqlTableEditor(IDbConnection db, IQueryBuilder provider)
{

View file

@ -1,5 +1,4 @@

/*
/*
TShock, a server mod for Terraria
Copyright (C) 2011 The TShock Team
@ -39,7 +38,10 @@ namespace TShockAPI.DB
new SqlColumn("Usergroup", MySqlDbType.Text),
new SqlColumn("IP", MySqlDbType.VarChar, 16)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "users.txt");
@ -73,9 +75,9 @@ namespace TShockAPI.DB
group = info[1];
}
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ?
"INSERT OR IGNORE INTO Users (Username, Password, Usergroup, IP) VALUES (@0, @1, @2, @3)" :
"INSERT IGNORE INTO Users SET Username=@0, Password=@1, Usergroup=@2, IP=@3";
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
? "INSERT OR IGNORE INTO Users (Username, Password, Usergroup, IP) VALUES (@0, @1, @2, @3)"
: "INSERT IGNORE INTO Users SET Username=@0, Password=@1, Usergroup=@2, IP=@3";
database.Query(query, username.Trim(), sha.Trim(), group.Trim(), ip.Trim());
}
@ -88,7 +90,6 @@ namespace TShockAPI.DB
File.Delete(file2);
File.Move(file, file2);
}
}
/// <summary>
@ -102,7 +103,9 @@ namespace TShockAPI.DB
if (!TShock.Groups.GroupExists(user.Group))
throw new GroupNotExistsException(user.Group);
if (database.Query("INSERT INTO Users (Username, Password, UserGroup, IP) VALUES (@0, @1, @2, @3);", user.Name, TShock.Utils.HashPassword(user.Password), user.Group, user.Address) < 1)
if (
database.Query("INSERT INTO Users (Username, Password, UserGroup, IP) VALUES (@0, @1, @2, @3);", user.Name,
TShock.Utils.HashPassword(user.Password), user.Group, user.Address) < 1)
throw new UserExistsException(user.Name);
}
catch (Exception ex)
@ -148,7 +151,9 @@ namespace TShockAPI.DB
{
try
{
if (database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", TShock.Utils.HashPassword(password), user.Name) == 0)
if (
database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", TShock.Utils.HashPassword(password),
user.Name) == 0)
throw new UserNotExistException(user.Name);
}
catch (Exception ex)
@ -255,6 +260,7 @@ namespace TShockAPI.DB
return null;
}
}
public User GetUserByID(int id)
{
try
@ -266,6 +272,7 @@ namespace TShockAPI.DB
return null;
}
}
public User GetUserByIP(string ip)
{
try
@ -277,6 +284,7 @@ namespace TShockAPI.DB
return null;
}
}
public User GetUser(User user)
{
try
@ -327,6 +335,7 @@ namespace TShockAPI.DB
Password = pass;
Group = group;
}
public User()
{
Address = "";
@ -342,14 +351,14 @@ namespace TShockAPI.DB
public UserManagerException(string message)
: base(message)
{
}
public UserManagerException(string message, Exception inner)
: base(message, inner)
{
}
}
}
}
[Serializable]
public class UserExistsException : UserManagerException
{
@ -358,6 +367,7 @@ namespace TShockAPI.DB
{
}
}
[Serializable]
public class UserNotExistException : UserManagerException
{
@ -366,6 +376,7 @@ namespace TShockAPI.DB
{
}
}
[Serializable]
public class GroupNotExistsException : UserManagerException
{

View file

@ -43,7 +43,10 @@ namespace TShockAPI.DB
new SqlColumn("WorldID", MySqlDbType.Text),
new SqlColumn("Private", MySqlDbType.Text)
);
var creator = new SqlTableCreator(db, db.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator());
var creator = new SqlTableCreator(db,
db.GetSqlType() == SqlType.Sqlite
? (IQueryBuilder) new SqliteQueryCreator()
: new MysqlQueryCreator());
creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "warps.xml");
@ -111,7 +114,6 @@ namespace TShockAPI.DB
break;
}
}
}
String path = Path.Combine(TShock.SavePath, "old_configs");
@ -167,17 +169,21 @@ namespace TShockAPI.DB
{
try
{
using (var reader = database.QueryReader("SELECT * FROM Warps WHERE WarpName=@0 AND WorldID=@1", name, Main.worldID.ToString()))
using (
var reader = database.QueryReader("SELECT * FROM Warps WHERE WarpName=@0 AND WorldID=@1", name,
Main.worldID.ToString()))
{
if (reader.Read())
{
try
{
return new Warp(new Vector2(reader.Get<int>("X"), reader.Get<int>("Y")), reader.Get<string>("WarpName"), reader.Get<string>("WorldID"), reader.Get<string>("Private"));
return new Warp(new Vector2(reader.Get<int>("X"), reader.Get<int>("Y")), reader.Get<string>("WarpName"),
reader.Get<string>("WorldID"), reader.Get<string>("Private"));
}
catch
{
return new Warp(new Vector2(reader.Get<int>("X"), reader.Get<int>("Y")), reader.Get<string>("WarpName"), reader.Get<string>("WorldID"), "0");
return new Warp(new Vector2(reader.Get<int>("X"), reader.Get<int>("Y")), reader.Get<string>("WarpName"),
reader.Get<string>("WorldID"), "0");
}
}
}

View file

@ -7,7 +7,6 @@ namespace TShockAPI.DB
{
public static class DbExt
{
/// <summary>
/// Executes a query on a database.
/// </summary>
@ -31,6 +30,7 @@ namespace TShockAPI.DB
}
}
}
/// <summary>
/// Executes a query on a database.
/// </summary>
@ -93,18 +93,49 @@ namespace TShockAPI.DB
return SqlType.Unknown;
}
static readonly Dictionary<Type, Func<IDataReader, int, object>> ReadFuncs = new Dictionary<Type, Func<IDataReader, int, object>>
private static readonly Dictionary<Type, Func<IDataReader, int, object>> ReadFuncs = new Dictionary
<Type, Func<IDataReader, int, object>>
{
{typeof(bool), (s, i) => s.GetBoolean(i)},
{typeof(byte), (s, i) => s.GetByte(i)},
{typeof(Int16), (s, i) => s.GetInt16(i)},
{typeof(Int32), (s, i) => s.GetInt32(i)},
{typeof(Int64), (s, i) => s.GetInt64(i)},
{typeof(string), (s, i) => s.GetString(i)},
{typeof(decimal), (s, i) => s.GetDecimal(i)},
{typeof(float), (s, i) => s.GetFloat(i)},
{typeof(double), (s, i) => s.GetDouble(i)},
{typeof(object), (s, i) => s.GetValue(i)},
{
typeof (bool),
(s, i) => s.GetBoolean(i)
},
{
typeof (byte),
(s, i) => s.GetByte(i)
},
{
typeof (Int16),
(s, i) => s.GetInt16(i)
},
{
typeof (Int32),
(s, i) => s.GetInt32(i)
},
{
typeof (Int64),
(s, i) => s.GetInt64(i)
},
{
typeof (string),
(s, i) => s.GetString(i)
},
{
typeof (decimal),
(s, i) => s.GetDecimal(i)
},
{
typeof (float),
(s, i) => s.GetFloat(i)
},
{
typeof (double),
(s, i) => s.GetDouble(i)
},
{
typeof (object),
(s, i) => s.GetValue(i)
},
};
public static T Get<T>(this IDataReader reader, string column)
@ -176,6 +207,7 @@ namespace TShockAPI.DB
return false;
return Reader.Read();
}
public T Get<T>(string column)
{
if (Reader == null)
@ -183,5 +215,4 @@ namespace TShockAPI.DB
return Reader.Get<T>(Reader.GetOrdinal(column));
}
}
}

View file

@ -22,11 +22,30 @@ namespace TShockAPI
{
public class FileTools
{
internal static string RulesPath { get { return Path.Combine(TShock.SavePath, "rules.txt"); } }
internal static string MotdPath { get { return Path.Combine(TShock.SavePath, "motd.txt"); } }
internal static string WhitelistPath { get { return Path.Combine(TShock.SavePath, "whitelist.txt"); } }
internal static string RememberedPosPath { get { return Path.Combine(TShock.SavePath, "oldpos.xml"); } }
internal static string ConfigPath { get { return Path.Combine(TShock.SavePath, "config.json"); } }
internal static string RulesPath
{
get { return Path.Combine(TShock.SavePath, "rules.txt"); }
}
internal static string MotdPath
{
get { return Path.Combine(TShock.SavePath, "motd.txt"); }
}
internal static string WhitelistPath
{
get { return Path.Combine(TShock.SavePath, "whitelist.txt"); }
}
internal static string RememberedPosPath
{
get { return Path.Combine(TShock.SavePath, "oldpos.xml"); }
}
internal static string ConfigPath
{
get { return Path.Combine(TShock.SavePath, "config.json"); }
}
public static void CreateFile(string file)
{
@ -52,7 +71,8 @@ namespace TShockAPI
}
CreateIfNot(RulesPath, "Respect the admins!\nDon't use TNT!");
CreateIfNot(MotdPath, "This server is running TShock. Type /help for a list of commands.\n%255,000,000%Current map: %map%\nCurrent players: %players%");
CreateIfNot(MotdPath,
"This server is running TShock. Type /help for a list of commands.\n%255,000,000%Current map: %map%\nCurrent players: %players%");
CreateIfNot(WhitelistPath);
try
@ -72,8 +92,6 @@ namespace TShockAPI
Log.Error("Config Exception");
Log.Error(ex.ToString());
}
}
/// <summary>

View file

@ -48,74 +48,131 @@ namespace MaxMind
/// </example>
public sealed class GeoIPCountry : IDisposable
{
Stream _geodata;
bool _close;
private Stream _geodata;
private bool _close;
// hard coded position of where country data starts in the data file.
const long COUNTRY_BEGIN = 16776960;
private const long COUNTRY_BEGIN = 16776960;
static readonly string[] CountryCodes = {
"--","AP","EU","AD","AE","AF","AG","AI","AL","AM","AN","AO","AQ","AR","AS",
"AT","AU","AW","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BM","BN",
"BO","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI",
"CK","CL","CM","CN","CO","CR","CU","CV","CX","CY","CZ","DE","DJ","DK","DM",
"DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR",
"FX","GA","GB","GD","GE","GF","GH","GI","GL","GM","GN","GP","GQ","GR","GS",
"GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IN","IO",
"IQ","IR","IS","IT","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR",
"KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA",
"MC","MD","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU",
"MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR",
"NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT",
"PW","PY","QA","RE","RO","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI",
"SJ","SK","SL","SM","SN","SO","SR","ST","SV","SY","SZ","TC","TD","TF","TG",
"TH","TJ","TK","TM","TN","TO","TL","TR","TT","TV","TW","TZ","UA","UG","UM",
"US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","YE","YT","RS",
"ZA","ZM","ME","ZW","A1","A2","O1","AX","GG","IM","JE","BL","MF"
private static readonly string[] CountryCodes = {
"--", "AP", "EU", "AD", "AE", "AF", "AG", "AI", "AL", "AM", "AN",
"AO", "AQ", "AR", "AS",
"AT", "AU", "AW", "AZ", "BA", "BB", "BD", "BE", "BF", "BG", "BH",
"BI", "BJ", "BM", "BN",
"BO", "BR", "BS", "BT", "BV", "BW", "BY", "BZ", "CA", "CC", "CD",
"CF", "CG", "CH", "CI",
"CK", "CL", "CM", "CN", "CO", "CR", "CU", "CV", "CX", "CY", "CZ",
"DE", "DJ", "DK", "DM",
"DO", "DZ", "EC", "EE", "EG", "EH", "ER", "ES", "ET", "FI", "FJ",
"FK", "FM", "FO", "FR",
"FX", "GA", "GB", "GD", "GE", "GF", "GH", "GI", "GL", "GM", "GN",
"GP", "GQ", "GR", "GS",
"GT", "GU", "GW", "GY", "HK", "HM", "HN", "HR", "HT", "HU", "ID",
"IE", "IL", "IN", "IO",
"IQ", "IR", "IS", "IT", "JM", "JO", "JP", "KE", "KG", "KH", "KI",
"KM", "KN", "KP", "KR",
"KW", "KY", "KZ", "LA", "LB", "LC", "LI", "LK", "LR", "LS", "LT",
"LU", "LV", "LY", "MA",
"MC", "MD", "MG", "MH", "MK", "ML", "MM", "MN", "MO", "MP", "MQ",
"MR", "MS", "MT", "MU",
"MV", "MW", "MX", "MY", "MZ", "NA", "NC", "NE", "NF", "NG", "NI",
"NL", "NO", "NP", "NR",
"NU", "NZ", "OM", "PA", "PE", "PF", "PG", "PH", "PK", "PL", "PM",
"PN", "PR", "PS", "PT",
"PW", "PY", "QA", "RE", "RO", "RU", "RW", "SA", "SB", "SC", "SD",
"SE", "SG", "SH", "SI",
"SJ", "SK", "SL", "SM", "SN", "SO", "SR", "ST", "SV", "SY", "SZ",
"TC", "TD", "TF", "TG",
"TH", "TJ", "TK", "TM", "TN", "TO", "TL", "TR", "TT", "TV", "TW",
"TZ", "UA", "UG", "UM",
"US", "UY", "UZ", "VA", "VC", "VE", "VG", "VI", "VN", "VU", "WF",
"WS", "YE", "YT", "RS",
"ZA", "ZM", "ME", "ZW", "A1", "A2", "O1", "AX", "GG", "IM", "JE",
"BL", "MF"
};
static readonly string[] CountryNames = {
"N/A","Asia/Pacific Region","Europe","Andorra","United Arab Emirates","Afghanistan",
"Antigua and Barbuda","Anguilla","Albania","Armenia","Netherlands Antilles","Angola",
"Antarctica","Argentina","American Samoa","Austria","Australia","Aruba","Azerbaijan",
"Bosnia and Herzegovina","Barbados","Bangladesh","Belgium","Burkina Faso","Bulgaria",
"Bahrain","Burundi","Benin","Bermuda","Brunei Darussalam","Bolivia","Brazil","Bahamas",
"Bhutan","Bouvet Island","Botswana","Belarus","Belize","Canada","Cocos (Keeling) Islands",
"Congo, The Democratic Republic of the","Central African Republic","Congo","Switzerland",
"Cote D'Ivoire","Cook Islands","Chile","Cameroon","China","Colombia","Costa Rica","Cuba",
"Cape Verde","Christmas Island","Cyprus","Czech Republic","Germany","Djibouti","Denmark",
"Dominica","Dominican Republic","Algeria","Ecuador","Estonia","Egypt","Western Sahara",
"Eritrea","Spain","Ethiopia","Finland","Fiji","Falkland Islands (Malvinas)",
"Micronesia, Federated States of","Faroe Islands","France","France, Metropolitan","Gabon",
"United Kingdom","Grenada","Georgia","French Guiana","Ghana","Gibraltar","Greenland",
private static readonly string[] CountryNames = {
"N/A", "Asia/Pacific Region", "Europe", "Andorra",
"United Arab Emirates", "Afghanistan",
"Antigua and Barbuda", "Anguilla", "Albania", "Armenia",
"Netherlands Antilles", "Angola",
"Antarctica", "Argentina", "American Samoa", "Austria", "Australia",
"Aruba", "Azerbaijan",
"Bosnia and Herzegovina", "Barbados", "Bangladesh", "Belgium",
"Burkina Faso", "Bulgaria",
"Bahrain", "Burundi", "Benin", "Bermuda", "Brunei Darussalam",
"Bolivia", "Brazil", "Bahamas",
"Bhutan", "Bouvet Island", "Botswana", "Belarus", "Belize", "Canada",
"Cocos (Keeling) Islands",
"Congo, The Democratic Republic of the", "Central African Republic",
"Congo", "Switzerland",
"Cote D'Ivoire", "Cook Islands", "Chile", "Cameroon", "China",
"Colombia", "Costa Rica", "Cuba",
"Cape Verde", "Christmas Island", "Cyprus", "Czech Republic",
"Germany", "Djibouti", "Denmark",
"Dominica", "Dominican Republic", "Algeria", "Ecuador", "Estonia",
"Egypt", "Western Sahara",
"Eritrea", "Spain", "Ethiopia", "Finland", "Fiji",
"Falkland Islands (Malvinas)",
"Micronesia, Federated States of", "Faroe Islands", "France",
"France, Metropolitan", "Gabon",
"United Kingdom", "Grenada", "Georgia", "French Guiana", "Ghana",
"Gibraltar", "Greenland",
"Gambia", "Guinea", "Guadeloupe", "Equatorial Guinea", "Greece",
"South Georgia and the South Sandwich Islands","Guatemala","Guam","Guinea-Bissau","Guyana",
"Hong Kong","Heard Island and McDonald Islands","Honduras","Croatia","Haiti","Hungary",
"Indonesia","Ireland","Israel","India","British Indian Ocean Territory","Iraq",
"Iran, Islamic Republic of","Iceland","Italy","Jamaica","Jordan","Japan","Kenya",
"Kyrgyzstan","Cambodia","Kiribati","Comoros","Saint Kitts and Nevis",
"Korea, Democratic People's Republic of","Korea, Republic of","Kuwait","Cayman Islands",
"Kazakstan","Lao People's Democratic Republic","Lebanon","Saint Lucia","Liechtenstein",
"Sri Lanka","Liberia","Lesotho","Lithuania","Luxembourg","Latvia","Libyan Arab Jamahiriya",
"Morocco","Monaco","Moldova, Republic of","Madagascar","Marshall Islands","Macedonia",
"Mali","Myanmar","Mongolia","Macau","Northern Mariana Islands","Martinique","Mauritania",
"Montserrat","Malta","Mauritius","Maldives","Malawi","Mexico","Malaysia","Mozambique",
"Namibia","New Caledonia","Niger","Norfolk Island","Nigeria","Nicaragua","Netherlands",
"Norway","Nepal","Nauru","Niue","New Zealand","Oman","Panama","Peru","French Polynesia",
"Papua New Guinea","Philippines","Pakistan","Poland","Saint Pierre and Miquelon",
"Pitcairn Islands","Puerto Rico","Palestinian Territory","Portugal","Palau","Paraguay",
"Qatar","Reunion","Romania","Russian Federation","Rwanda","Saudi Arabia",
"Solomon Islands","Seychelles","Sudan","Sweden","Singapore","Saint Helena","Slovenia",
"Svalbard and Jan Mayen","Slovakia","Sierra Leone","San Marino","Senegal","Somalia",
"Suriname","Sao Tome and Principe","El Salvador","Syrian Arab Republic","Swaziland",
"Turks and Caicos Islands","Chad","French Southern Territories","Togo","Thailand",
"Tajikistan","Tokelau","Turkmenistan","Tunisia","Tonga","Timor-Leste","Turkey",
"Trinidad and Tobago","Tuvalu","Taiwan","Tanzania, United Republic of","Ukraine","Uganda",
"United States Minor Outlying Islands","United States","Uruguay","Uzbekistan",
"Holy See (Vatican City State)","Saint Vincent and the Grenadines","Venezuela",
"Virgin Islands, British","Virgin Islands, U.S.","Vietnam","Vanuatu","Wallis and Futuna",
"Samoa","Yemen","Mayotte","Serbia","South Africa","Zambia","Montenegro","Zimbabwe",
"Anonymous Proxy","Satellite Provider","Other","Aland Islands","Guernsey","Isle of Man",
"South Georgia and the South Sandwich Islands", "Guatemala", "Guam",
"Guinea-Bissau", "Guyana",
"Hong Kong", "Heard Island and McDonald Islands", "Honduras",
"Croatia", "Haiti", "Hungary",
"Indonesia", "Ireland", "Israel", "India",
"British Indian Ocean Territory", "Iraq",
"Iran, Islamic Republic of", "Iceland", "Italy", "Jamaica", "Jordan",
"Japan", "Kenya",
"Kyrgyzstan", "Cambodia", "Kiribati", "Comoros",
"Saint Kitts and Nevis",
"Korea, Democratic People's Republic of", "Korea, Republic of",
"Kuwait", "Cayman Islands",
"Kazakstan", "Lao People's Democratic Republic", "Lebanon",
"Saint Lucia", "Liechtenstein",
"Sri Lanka", "Liberia", "Lesotho", "Lithuania", "Luxembourg",
"Latvia", "Libyan Arab Jamahiriya",
"Morocco", "Monaco", "Moldova, Republic of", "Madagascar",
"Marshall Islands", "Macedonia",
"Mali", "Myanmar", "Mongolia", "Macau", "Northern Mariana Islands",
"Martinique", "Mauritania",
"Montserrat", "Malta", "Mauritius", "Maldives", "Malawi", "Mexico",
"Malaysia", "Mozambique",
"Namibia", "New Caledonia", "Niger", "Norfolk Island", "Nigeria",
"Nicaragua", "Netherlands",
"Norway", "Nepal", "Nauru", "Niue", "New Zealand", "Oman", "Panama",
"Peru", "French Polynesia",
"Papua New Guinea", "Philippines", "Pakistan", "Poland",
"Saint Pierre and Miquelon",
"Pitcairn Islands", "Puerto Rico", "Palestinian Territory",
"Portugal", "Palau", "Paraguay",
"Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda",
"Saudi Arabia",
"Solomon Islands", "Seychelles", "Sudan", "Sweden", "Singapore",
"Saint Helena", "Slovenia",
"Svalbard and Jan Mayen", "Slovakia", "Sierra Leone", "San Marino",
"Senegal", "Somalia",
"Suriname", "Sao Tome and Principe", "El Salvador",
"Syrian Arab Republic", "Swaziland",
"Turks and Caicos Islands", "Chad", "French Southern Territories",
"Togo", "Thailand",
"Tajikistan", "Tokelau", "Turkmenistan", "Tunisia", "Tonga",
"Timor-Leste", "Turkey",
"Trinidad and Tobago", "Tuvalu", "Taiwan",
"Tanzania, United Republic of", "Ukraine", "Uganda",
"United States Minor Outlying Islands", "United States", "Uruguay",
"Uzbekistan",
"Holy See (Vatican City State)", "Saint Vincent and the Grenadines",
"Venezuela",
"Virgin Islands, British", "Virgin Islands, U.S.", "Vietnam",
"Vanuatu", "Wallis and Futuna",
"Samoa", "Yemen", "Mayotte", "Serbia", "South Africa", "Zambia",
"Montenegro", "Zimbabwe",
"Anonymous Proxy", "Satellite Provider", "Other", "Aland Islands",
"Guernsey", "Isle of Man",
"Jersey", "Saint Barthelemy", "Saint Martin"
};
@ -185,13 +242,13 @@ namespace MaxMind
return index == -1 ? null : CountryNames[index];
}
int FindIndex(IPAddress ip)
private int FindIndex(IPAddress ip)
{
return (int) FindCountryCode(0, AddressToLong(ip), 31);
}
// Converts an IPv4 address into a long, for reading from geo database
long AddressToLong(IPAddress ip)
private long AddressToLong(IPAddress ip)
{
if (ip.AddressFamily != AddressFamily.InterNetwork)
throw new InvalidOperationException("IP address is not IPv4");
@ -211,7 +268,7 @@ namespace MaxMind
// Traverses the GeoIP binary data looking for a country code based
// on the IP address mask
long FindCountryCode(long offset, long ipnum, int depth)
private long FindCountryCode(long offset, long ipnum, int depth)
{
byte[] buffer = new byte[6]; // 2 * MAX_RECORD_LENGTH
long[] x = new long[2];
@ -257,4 +314,3 @@ namespace MaxMind
}
}
}

View file

@ -27,6 +27,7 @@ using TShockAPI.Net;
namespace TShockAPI
{
public delegate bool GetDataHandlerDelegate(GetDataHandlerArgs args);
public class GetDataHandlerArgs : EventArgs
{
public TSPlayer Player { get; private set; }
@ -43,6 +44,7 @@ namespace TShockAPI
Data = data;
}
}
public static class GetDataHandlers
{
private static Dictionary<PacketTypes, GetDataHandlerDelegate> GetDataHandlerDelegates;
@ -348,7 +350,8 @@ namespace TShockAPI
TShock.HackedInventory(args.Player);
}
if (TShock.Utils.ActivePlayers() + 1 > TShock.Config.MaxSlots && !args.Player.Group.HasPermission(Permissions.reservedslot))
if (TShock.Utils.ActivePlayers() + 1 > TShock.Config.MaxSlots &&
!args.Player.Group.HasPermission(Permissions.reservedslot))
{
TShock.Utils.ForceKick(args.Player, TShock.Config.ServerFullReason);
return true;
@ -358,12 +361,15 @@ namespace TShockAPI
if (TShock.Config.EnableGeoIP && TShock.Geo != null)
{
Log.Info(string.Format("{0} ({1}) from '{2}' group from '{3}' joined. ({4}/{5})", args.Player.Name, args.Player.IP, args.Player.Group.Name, args.Player.Country, TShock.Utils.ActivePlayers(), TShock.Config.MaxSlots));
Log.Info(string.Format("{0} ({1}) from '{2}' group from '{3}' joined. ({4}/{5})", args.Player.Name, args.Player.IP,
args.Player.Group.Name, args.Player.Country, TShock.Utils.ActivePlayers(),
TShock.Config.MaxSlots));
TShock.Utils.Broadcast(args.Player.Name + " has joined from the " + args.Player.Country, Color.Yellow);
}
else
{
Log.Info(string.Format("{0} ({1}) from '{2}' group joined. ({3}/{4})", args.Player.Name, args.Player.IP, args.Player.Group.Name, TShock.Utils.ActivePlayers(), TShock.Config.MaxSlots));
Log.Info(string.Format("{0} ({1}) from '{2}' group joined. ({3}/{4})", args.Player.Name, args.Player.IP,
args.Player.Group.Name, TShock.Utils.ActivePlayers(), TShock.Config.MaxSlots));
TShock.Utils.Broadcast(args.Player.Name + " has joined", Color.Yellow);
}
@ -603,7 +609,8 @@ namespace TShockAPI
args.Player.SendTileSquare(tileX, tileY);
return true;
}
if (tiletype == 48 && !args.Player.Group.HasPermission(Permissions.usebanneditem) && TShock.Itembans.ItemIsBanned("Spike", args.Player))
if (tiletype == 48 && !args.Player.Group.HasPermission(Permissions.usebanneditem) &&
TShock.Itembans.ItemIsBanned("Spike", args.Player))
{
args.Player.Disable();
args.Player.SendTileSquare(tileX, tileY);
@ -615,7 +622,8 @@ namespace TShockAPI
args.Player.SendTileSquare(tileX, tileY);
return true;
}
if (tiletype == 141 && !args.Player.Group.HasPermission(Permissions.usebanneditem) && TShock.Itembans.ItemIsBanned("Explosives", args.Player))
if (tiletype == 141 && !args.Player.Group.HasPermission(Permissions.usebanneditem) &&
TShock.Itembans.ItemIsBanned("Explosives", args.Player))
{
args.Player.Disable();
args.Player.SendTileSquare(tileX, tileY);
@ -674,7 +682,8 @@ namespace TShockAPI
args.Player.TilesCreated.Add(coords, Main.tile[tileX, tileY].Data);
}
if ((type == 0 || type == 4) && Main.tileSolid[Main.tile[tileX, tileY].type] && !args.Player.Group.HasPermission(Permissions.ignorekilltiledetection))
if ((type == 0 || type == 4) && Main.tileSolid[Main.tile[tileX, tileY].type] &&
!args.Player.Group.HasPermission(Permissions.ignorekilltiledetection))
{
args.Player.TileKillThreshold++;
var coords = new Vector2(tileX, tileY);
@ -705,7 +714,8 @@ namespace TShockAPI
long seconds = (long) (DateTime.UtcNow - args.Player.LastPvpChange).TotalSeconds;
if (seconds > 5)
{
TSPlayer.All.SendMessage(string.Format("{0} has {1} PvP!", args.Player.Name, pvp ? "enabled" : "disabled"), Main.teamColor[args.Player.Team]);
TSPlayer.All.SendMessage(string.Format("{0} has {1} PvP!", args.Player.Name, pvp ? "enabled" : "disabled"),
Main.teamColor[args.Player.Team]);
}
args.Player.LastPvpChange = DateTime.UtcNow;
}
@ -743,7 +753,8 @@ namespace TShockAPI
if (!pos.Equals(args.Player.LastNetPosition))
{
float distance = Vector2.Distance(new Vector2(pos.X / 16f, pos.Y / 16f), new Vector2(args.Player.LastNetPosition.X / 16f, args.Player.LastNetPosition.Y / 16f));
float distance = Vector2.Distance(new Vector2(pos.X/16f, pos.Y/16f),
new Vector2(args.Player.LastNetPosition.X/16f, args.Player.LastNetPosition.Y/16f));
if (TShock.CheckIgnores(args.Player))
{
if (distance > TShock.Config.MaxRangeForDisabled)
@ -793,7 +804,8 @@ namespace TShockAPI
return true;
}
if (!args.Player.Group.HasPermission(Permissions.ignorenoclipdetection) && Collision.SolidCollision(pos, args.TPlayer.width, args.TPlayer.height))
if (!args.Player.Group.HasPermission(Permissions.ignorenoclipdetection) &&
Collision.SolidCollision(pos, args.TPlayer.width, args.TPlayer.height))
{
int lastTileX = (int) (args.Player.LastNetPosition.X/16f);
int lastTileY = (int) (args.Player.LastNetPosition.Y/16f);
@ -809,11 +821,14 @@ namespace TShockAPI
if ((control & 32) == 32)
{
if (!args.Player.Group.HasPermission(Permissions.usebanneditem) && TShock.Itembans.ItemIsBanned(args.TPlayer.inventory[item].name, args.Player))
if (!args.Player.Group.HasPermission(Permissions.usebanneditem) &&
TShock.Itembans.ItemIsBanned(args.TPlayer.inventory[item].name, args.Player))
{
control -= 32;
args.Player.Disable();
args.Player.SendMessage(string.Format("You cannot use {0} on this server. Your actions are being ignored.", args.TPlayer.inventory[item].name), Color.Red);
args.Player.SendMessage(
string.Format("You cannot use {0} on this server. Your actions are being ignored.",
args.TPlayer.inventory[item].name), Color.Red);
}
}
@ -1042,14 +1057,16 @@ namespace TShockAPI
bucket = 2;
}
if (lava && bucket != 2 && !args.Player.Group.HasPermission(Permissions.usebanneditem) && TShock.Itembans.ItemIsBanned("Lava Bucket", args.Player))
if (lava && bucket != 2 && !args.Player.Group.HasPermission(Permissions.usebanneditem) &&
TShock.Itembans.ItemIsBanned("Lava Bucket", args.Player))
{
args.Player.Disable();
args.Player.SendTileSquare(tileX, tileY);
return true;
}
if (!lava && bucket != 1 && !args.Player.Group.HasPermission(Permissions.usebanneditem) && TShock.Itembans.ItemIsBanned("Water Bucket", args.Player))
if (!lava && bucket != 1 && !args.Player.Group.HasPermission(Permissions.usebanneditem) &&
TShock.Itembans.ItemIsBanned("Water Bucket", args.Player))
{
args.Player.Disable();
args.Player.SendTileSquare(tileX, tileY);
@ -1236,19 +1253,22 @@ namespace TShockAPI
if (!args.Player.Group.HasPermission(Permissions.movenpc))
{
args.Player.SendMessage("You do not have permission to relocate NPCs.", Color.Red);
args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY, Convert.ToByte(Main.npc[id].homeless));
args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
Convert.ToByte(Main.npc[id].homeless));
return true;
}
if (TShock.CheckTilePermission(args.Player, x, y))
{
args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY, Convert.ToByte(Main.npc[id].homeless));
args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
Convert.ToByte(Main.npc[id].homeless));
return true;
}
if (TShock.CheckRangePermission(args.Player, x, y))
{
args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY, Convert.ToByte(Main.npc[id].homeless));
args.Player.SendData(PacketTypes.UpdateNPCHome, "", id, Main.npc[id].homeTileX, Main.npc[id].homeTileY,
Convert.ToByte(Main.npc[id].homeless));
return true;
}
return false;
@ -1418,7 +1438,9 @@ namespace TShockAPI
return true;
}
if (TShock.Config.RangeChecks && TShock.CheckRangePermission(args.Player, (int)(Main.npc[id].position.X / 16f), (int)(Main.npc[id].position.Y / 16f), 100))
if (TShock.Config.RangeChecks &&
TShock.CheckRangePermission(args.Player, (int) (Main.npc[id].position.X/16f), (int) (Main.npc[id].position.Y/16f),
100))
{
args.Player.SendData(PacketTypes.NpcUpdate, "", id);
return true;
@ -1474,7 +1496,8 @@ namespace TShockAPI
if (buff == 10)
{
if (!args.Player.Group.HasPermission(Permissions.usebanneditem) && TShock.Itembans.ItemIsBanned("Invisibility Potion", args.Player) )
if (!args.Player.Group.HasPermission(Permissions.usebanneditem) &&
TShock.Itembans.ItemIsBanned("Invisibility Potion", args.Player))
buff = 0;
else if (TShock.Config.DisableInvisPvP && args.TPlayer.hostile)
buff = 0;

View file

@ -75,6 +75,7 @@ namespace TShockAPI
{
permissions.Add(permission);
}
public void SetPermission(List<string> permission)
{
permissions.Clear();
@ -95,7 +96,6 @@ namespace TShockAPI
B = (byte) TShock.Config.SuperAdminChatRGB[2];
Prefix = TShock.Config.SuperAdminChatPrefix;
Suffix = TShock.Config.SuperAdminChatSuffix;
}
public override bool HasPermission(string permission)

View file

@ -30,6 +30,7 @@ namespace TShockAPI
/// </summary>
/// <param name="stream">Stream to write to</param>
void Pack(Stream stream);
/// <summary>
/// Reads object information from the stream
/// </summary>

View file

@ -10,6 +10,7 @@ namespace TShockAPI.Net
{
get { throw new NotImplementedException("Msg ID not implemented"); }
}
public void PackFull(Stream stream)
{
long start = stream.Position;

View file

@ -4,16 +4,15 @@ using System.Text;
namespace TShockAPI.Net
{
class DisconnectMsg : BaseMsg
internal class DisconnectMsg : BaseMsg
{
public override PacketTypes ID
{
get
{
return PacketTypes.Disconnect;
}
get { return PacketTypes.Disconnect; }
}
public string Reason { get; set; }
public override void Pack(Stream stream)
{
stream.WriteBytes(Encoding.ASCII.GetBytes(Reason));

View file

@ -34,9 +34,20 @@ namespace TShockAPI.Net
public bool Lava { get; set; }
public bool Wire { get; set; }
public bool HasWall { get { return Wall > 0; } }
public bool HasLiquid { get { return Liquid > 0; } }
public bool FrameImportant { get { return Main.tileFrameImportant[Type]; } }
public bool HasWall
{
get { return Wall > 0; }
}
public bool HasLiquid
{
get { return Liquid > 0; }
}
public bool FrameImportant
{
get { return Main.tileFrameImportant[Type]; }
}
public NetTile()
{

View file

@ -7,10 +7,7 @@ namespace TShockAPI.Net
{
public override PacketTypes ID
{
get
{
return PacketTypes.ProjectileNew;
}
get { return PacketTypes.ProjectileNew; }
}
public short Index { get; set; }

View file

@ -7,10 +7,7 @@ namespace TShockAPI.Net
{
public override PacketTypes ID
{
get
{
return PacketTypes.PlayerSpawn;
}
get { return PacketTypes.PlayerSpawn; }
}
public int TileX { get; set; }

View file

@ -34,6 +34,7 @@ namespace TShockAPI.Net
HardMode = 16,
DownedClown = 32
}
public class WorldInfoMsg : BaseMsg
{
public int Time { get; set; }
@ -49,13 +50,12 @@ namespace TShockAPI.Net
public int WorldID { get; set; }
public WorldInfoFlag WorldFlags { get; set; }
public string WorldName { get; set; }
public override PacketTypes ID
{
get
{
return PacketTypes.WorldInfo;
}
get { return PacketTypes.WorldInfo; }
}
public override void Pack(Stream stream)
{
stream.WriteInt32(Time);

View file

@ -16,11 +16,11 @@ namespace TShockAPI
/// </summary>
public int BytesPerUpdate { get; set; }
PacketBuffer[] buffers = new PacketBuffer[Netplay.serverSock.Length];
private PacketBuffer[] buffers = new PacketBuffer[Netplay.serverSock.Length];
int[] Bytes = new int[52];
int[] Packets = new int[52];
int[] Compressed = new int[52];
private int[] Bytes = new int[52];
private int[] Packets = new int[52];
private int[] Compressed = new int[52];
#if DEBUG_NET
Command dump;
@ -70,25 +70,26 @@ namespace TShockAPI
}
}
void Dump(CommandArgs args)
private void Dump(CommandArgs args)
{
var sb = new StringBuilder();
sb.AppendLine("{0,-25}{1,-25}{2,-25}{3}".SFormat("Name:", "Packets", "Bytes", "Compression"));
for (int i = 1; i < Bytes.Length; i++)
{
sb.AppendLine("{0,-25}{1,-25}{2,-25}{3}".SFormat(Enum.GetName(typeof(PacketTypes), i) + ":", Packets[i], Bytes[i], Compressed[i]));
sb.AppendLine("{0,-25}{1,-25}{2,-25}{3}".SFormat(Enum.GetName(typeof (PacketTypes), i) + ":", Packets[i], Bytes[i],
Compressed[i]));
}
File.WriteAllText(Path.Combine(TShock.SavePath, "dmp.txt"), sb.ToString());
}
void Flush(CommandArgs args)
private void Flush(CommandArgs args)
{
Bytes = new int[52];
Packets = new int[52];
Compressed = new int[52];
}
void GameHooks_Update()
private void GameHooks_Update()
{
FlushAll();
}
@ -129,7 +130,7 @@ namespace TShockAPI
}
void ServerHooks_SocketReset(ServerSock socket)
private void ServerHooks_SocketReset(ServerSock socket)
{
buffers[socket.whoAmI] = new PacketBuffer();
}
@ -138,6 +139,7 @@ namespace TShockAPI
{
return SendBytes(socket, buffer, 0, buffer.Length);
}
public void BufferBytes(ServerSock socket, byte[] buffer)
{
BufferBytes(socket, buffer, 0, buffer.Length);
@ -187,11 +189,12 @@ namespace TShockAPI
return false;
}
void ServerHooks_SendBytes(ServerSock socket, byte[] buffer, int offset, int count, HandledEventArgs e)
private void ServerHooks_SendBytes(ServerSock socket, byte[] buffer, int offset, int count, HandledEventArgs e)
{
e.Handled = true;
BufferBytes(socket, buffer, offset, count);
}
#if DEBUG_NET
static int Compress(byte[] buffer, int offset, int count)
{

View file

@ -11,173 +11,126 @@ namespace TShockAPI
{
//Permissions with blank descriptions basically means its described by the commands it gives access to.
[Description("")]
public static readonly string causeevents;
[Description("")] public static readonly string causeevents;
[Description("Required to be able to build (modify tiles and liquid)")]
public static readonly string canbuild;
[Description("Required to be able to build (modify tiles and liquid)")] public static readonly string canbuild;
[Description("")]
public static readonly string kill;
[Description("")] public static readonly string kill;
[Description("Allows you to use banned items")]
public static readonly string usebanneditem;
[Description("Allows you to use banned items")] public static readonly string usebanneditem;
[Description("Allows you to edit the spawn")]
public static readonly string editspawn;
[Description("Allows you to edit the spawn")] public static readonly string editspawn;
[Description("Prevents you from being kicked")]
public static readonly string immunetokick;
[Description("Prevents you from being kicked")] public static readonly string immunetokick;
[Description("Prevents you from being banned")]
public static readonly string immunetoban;
[Description("Prevents you from being banned")] public static readonly string immunetoban;
[Description("Prevents you from being reverted by kill tile abuse detection")]
public static readonly string ignorekilltiledetection;
[Description("Prevents you from being reverted by kill tile abuse detection")] public static readonly string
ignorekilltiledetection;
[Description("Prevents you from being reverted by place tile abuse detection")]
public static readonly string ignoreplacetiledetection;
[Description("Prevents you from being reverted by place tile abuse detection")] public static readonly string
ignoreplacetiledetection;
[Description("Prevents you from being disabled by liquid set abuse detection")]
public static readonly string ignoreliquidsetdetection;
[Description("Prevents you from being disabled by liquid set abuse detection")] public static readonly string
ignoreliquidsetdetection;
[Description("Prevents you from being disabled by liquid set abuse detection")]
public static readonly string ignoreprojectiledetection;
[Description("Prevents you from being disabled by liquid set abuse detection")] public static readonly string
ignoreprojectiledetection;
[Description("Prevents you from being reverted by no clip detection")]
public static readonly string ignorenoclipdetection;
[Description("Prevents you from being reverted by no clip detection")] public static readonly string
ignorenoclipdetection;
[Description("Prevents you from being disabled by stack hack detection")]
public static readonly string ignorestackhackdetection;
[Description("Prevents you from being disabled by stack hack detection")] public static readonly string
ignorestackhackdetection;
[Description("Prevents you from being kicked by hacked health detection")]
public static readonly string ignorestathackdetection;
[Description("Prevents you from being kicked by hacked health detection")] public static readonly string
ignorestathackdetection;
[Description("Specific log messages are sent to users with this permission")]
public static readonly string logs;
[Description("Specific log messages are sent to users with this permission")] public static readonly string logs;
[Description("Allows you to bypass the max slots for up to 5 slots above your max")]
public static readonly string reservedslot;
[Description("Allows you to bypass the max slots for up to 5 slots above your max")] public static readonly string
reservedslot;
[Description("User is notified when an update is available")]
public static readonly string maintenance;
[Description("User is notified when an update is available")] public static readonly string maintenance;
[Description("User can kick others")]
public static readonly string kick;
[Description("User can kick others")] public static readonly string kick;
[Description("User can ban others")]
public static readonly string ban;
[Description("User can ban others")] public static readonly string ban;
[Description("User can modify the whitelist")]
public static readonly string whitelist;
[Description("User can modify the whitelist")] public static readonly string whitelist;
[Description("User can spawn bosses")]
public static readonly string spawnboss;
[Description("User can spawn bosses")] public static readonly string spawnboss;
[Description("User can spawn npcs")]
public static readonly string spawnmob;
[Description("User can spawn npcs")] public static readonly string spawnmob;
[Description("User can teleport")]
public static readonly string tp;
[Description("User can teleport")] public static readonly string tp;
[Description("User can teleport people to them")]
public static readonly string tphere;
[Description("User can teleport people to them")] public static readonly string tphere;
[Description("User can use warps")]
public static readonly string warp;
[Description("User can use warps")] public static readonly string warp;
[Description("User can manage warps")]
public static readonly string managewarp;
[Description("User can manage warps")] public static readonly string managewarp;
[Description("User can manage item bans")]
public static readonly string manageitem;
[Description("User can manage item bans")] public static readonly string manageitem;
[Description("User can manage groups")]
public static readonly string managegroup;
[Description("User can manage groups")] public static readonly string managegroup;
[Description("User can edit sevrer configurations")]
public static readonly string cfg;
[Description("User can edit sevrer configurations")] public static readonly string cfg;
[Description("")]
public static readonly string time;
[Description("")] public static readonly string time;
[Description("")]
public static readonly string pvpfun;
[Description("")] public static readonly string pvpfun;
[Description("User can edit regions")]
public static readonly string manageregion;
[Description("User can edit regions")] public static readonly string manageregion;
[Description("Meant for super admins only")]
public static readonly string rootonly;
[Description("Meant for super admins only")] public static readonly string rootonly;
[Description("User can whisper to others")]
public static readonly string whisper;
[Description("User can whisper to others")] public static readonly string whisper;
[Description("")]
public static readonly string annoy;
[Description("")] public static readonly string annoy;
[Description("User can kill all enemy npcs")]
public static readonly string butcher;
[Description("User can kill all enemy npcs")] public static readonly string butcher;
[Description("User can spawn items")]
public static readonly string item;
[Description("User can spawn items")] public static readonly string item;
[Description("User can clear item drops.")]
public static readonly string clearitems;
[Description("User can clear item drops.")] public static readonly string clearitems;
[Description("")]
public static readonly string heal;
[Description("")] public static readonly string heal;
[Description("User can buff self")]
public static readonly string buff;
[Description("User can buff self")] public static readonly string buff;
[Description("User can buff other players")]
public static readonly string buffplayer;
[Description("User can buff other players")] public static readonly string buffplayer;
[Description("")]
public static readonly string grow;
[Description("")] public static readonly string grow;
[Description("User can change hardmode state.")]
public static readonly string hardmode;
[Description("User can change hardmode state.")] public static readonly string hardmode;
[Description("User can change the homes of NPCs.")]
public static readonly string movenpc;
[Description("User can change the homes of NPCs.")] public static readonly string movenpc;
[Description("Users can stop people from TPing to them")]
public static readonly string tpallow;
[Description("Users can stop people from TPing to them")] public static readonly string tpallow;
[Description("Users can tp to anyone")]
public static readonly string tpall;
[Description("Users can tp to anyone")] public static readonly string tpall;
[Description("Users can tp to people without showing a notice")]
public static readonly string tphide;
[Description("Users can tp to people without showing a notice")] public static readonly string tphide;
[Description("User can convert hallow into corruption and vice-versa")]
public static readonly string converthardmode;
[Description("User can convert hallow into corruption and vice-versa")] public static readonly string converthardmode;
[Description("User can mute and unmute users")]
public static readonly string mute;
[Description("User can mute and unmute users")] public static readonly string mute;
[Description("User can register account in game")]
public static readonly string canregister;
[Description("User can register account in game")] public static readonly string canregister;
[Description("User can login in game")]
public static readonly string canlogin;
[Description("User can login in game")] public static readonly string canlogin;
[Description("User can change password in game")]
public static readonly string canchangepassword;
[Description("User can change password in game")] public static readonly string canchangepassword;
[Description("User can use party chat in game")]
public static readonly string canpartychat;
[Description("User can use party chat in game")] public static readonly string canpartychat;
[Description("User can talk in third person")]
public static readonly string cantalkinthird;
[Description("User can talk in third person")] public static readonly string cantalkinthird;
[Description("Bypass Server Side Inventory checks")]
public static readonly string bypassinventorychecks;
[Description("Bypass Server Side Inventory checks")] public static readonly string bypassinventorychecks;
[Description("Allow unrestricted Send Tile Square usage, for client side world editing")]
public static readonly string allowclientsideworldedit;
[Description("Allow unrestricted Send Tile Square usage, for client side world editing")] public static readonly
string allowclientsideworldedit;
static Permissions()
@ -188,21 +141,22 @@ namespace TShockAPI
}
}
static List<Command> GetCommands(string perm)
private static List<Command> GetCommands(string perm)
{
if (Commands.ChatCommands.Count < 1)
Commands.InitCommands();
return Commands.ChatCommands.Where(c => c.Permission == perm).ToList();
}
static void DumpDescriptions()
private static void DumpDescriptions()
{
var sb = new StringBuilder();
foreach (var field in typeof (Permissions).GetFields())
{
var name = field.Name;
var descattr = field.GetCustomAttributes(false).FirstOrDefault(o => o is DescriptionAttribute) as DescriptionAttribute;
var descattr =
field.GetCustomAttributes(false).FirstOrDefault(o => o is DescriptionAttribute) as DescriptionAttribute;
var desc = descattr != null && !string.IsNullOrWhiteSpace(descattr.Description) ? descattr.Description : "None";
var commands = GetCommands(name);
@ -213,7 +167,10 @@ namespace TShockAPI
c.Names[i] = "/" + c.Names[i];
}
}
var strs = commands.Select(c => c.Name + (c.Names.Count > 1 ? "({0})".SFormat(string.Join(" ", c.Names.ToArray(), 1, c.Names.Count - 1)) : ""));
var strs =
commands.Select(
c =>
c.Name + (c.Names.Count > 1 ? "({0})".SFormat(string.Join(" ", c.Names.ToArray(), 1, c.Names.Count - 1)) : ""));
sb.AppendLine("## <a name=\"{0}\">{0} ".SFormat(name));
sb.AppendLine("**Description:** {0} ".SFormat(desc));
@ -233,12 +190,10 @@ namespace TShockAPI
public TodoAttribute(string info)
{
Info = info;
}
public TodoAttribute()
{
}
}
}

View file

@ -28,7 +28,7 @@ using Terraria;
namespace TShockAPI
{
class RconHandler
internal class RconHandler
{
public static string Password = "";
private static DateTime LastRequest;
@ -125,7 +125,6 @@ namespace TShockAPI
Log.Error(e.ToString());
}
}
}
private static string SendPacket(byte[] bytes, string hostname, int port)
@ -157,7 +156,8 @@ namespace TShockAPI
var print = true;
if ((DateTime.Now - LastRequest).Milliseconds >= 100)
{
if (packetstring.StartsWith("rcon") || packetstring.Substring(4).StartsWith("rcon") || packetstring.Substring(5).StartsWith("rcon"))
if (packetstring.StartsWith("rcon") || packetstring.Substring(4).StartsWith("rcon") ||
packetstring.Substring(5).StartsWith("rcon"))
{
if (!string.IsNullOrEmpty(Password))
{
@ -202,7 +202,9 @@ namespace TShockAPI
if (packetstring.Split(' ').Length == 2)
challenge = packetstring.Split(' ')[1];
response = "infoResponse\n";
var infostring = string.Format(@"\_TShock_ver\{6}\mapname\{1}\sv_maxclients\{2}\clients\{3}\sv_privateClients\{4}\hconly\{5}\gamename\TERRARIA\protocol\100\sv_hostname\{0}\g_needPass\{7}",
var infostring =
string.Format(
@"\_TShock_ver\{6}\mapname\{1}\sv_maxclients\{2}\clients\{3}\sv_privateClients\{4}\hconly\{5}\gamename\TERRARIA\protocol\100\sv_hostname\{0}\g_needPass\{7}",
TShock.Config.ServerName, Main.worldName, Main.maxNetPlayers,
TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots,
TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum,
@ -221,7 +223,8 @@ namespace TShockAPI
if (packetstring.Split(' ').Length == 2)
challenge = packetstring.Split(' ')[1];
response = "statusResponse\n";
var statusstring = string.Format(@"\_TShock_ver\{6}\mapname\{1}\sv_maxclients\{2}\clients\{3}\sv_privateClients\{4}\hconly\{5}\gamename\TERRARIA\protocol\100\sv_hostname\{0}\g_needPass\{7}",
var statusstring = string.Format(
@"\_TShock_ver\{6}\mapname\{1}\sv_maxclients\{2}\clients\{3}\sv_privateClients\{4}\hconly\{5}\gamename\TERRARIA\protocol\100\sv_hostname\{0}\g_needPass\{7}",
TShock.Config.ServerName, Main.worldName, Main.maxNetPlayers,
TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots,
TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum,
@ -264,7 +267,8 @@ namespace TShockAPI
if (player != null && player.Active)
{
count++;
TSPlayer.Server.SendMessage(string.Format("{0} ({1}) [{2}] <{3}>", player.Name, player.IP, player.Group.Name, player.UserAccountName));
TSPlayer.Server.SendMessage(string.Format("{0} ({1}) [{2}] <{3}>", player.Name, player.IP, player.Group.Name,
player.UserAccountName));
}
}
TSPlayer.Server.SendMessage(string.Format("{0} players connected.", count));
@ -279,7 +283,9 @@ namespace TShockAPI
if (player != null && player.Active)
{
count++;
Response += (string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name, Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint, "")) + "\n";
Response +=
(string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name,
Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint, "")) + "\n";
}
}
}
@ -299,8 +305,7 @@ namespace TShockAPI
if (!Commands.HandleCommand(TSPlayer.Server, text))
return "Invalid command.";
}
else
if (!Commands.HandleCommand(TSPlayer.Server, "/" + text))
else if (!Commands.HandleCommand(TSPlayer.Server, "/" + text))
return "Invalid command.";
return "";
}
@ -368,6 +373,7 @@ namespace TShockAPI
}
#region ParseParams
private static List<String> ParseParameters(string str)
{
var ret = new List<string>();
@ -424,6 +430,7 @@ namespace TShockAPI
return ret;
}
private static char GetEscape(char c)
{
switch (c)
@ -438,10 +445,12 @@ namespace TShockAPI
return c;
}
}
private static bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t' || c == '\n';
}
#endregion
}
}

View file

@ -17,10 +17,11 @@ namespace Rests
/// <param name="verbs">{x} in urltemplate</param>
/// <returns>Response object or null to not handle request</returns>
public delegate object RestCommandD(RestVerbs verbs, IParameterCollection parameters);
public class Rest : IDisposable
{
readonly List<RestCommand> commands = new List<RestCommand>();
HttpListener listener;
private readonly List<RestCommand> commands = new List<RestCommand>();
private HttpListener listener;
public IPAddress Ip { get; set; }
public int Port { get; set; }
@ -29,6 +30,7 @@ namespace Rests
Ip = ip;
Port = port;
}
public virtual void Start()
{
if (listener == null)
@ -38,12 +40,14 @@ namespace Rests
listener.Start(int.MaxValue);
}
}
public void Start(IPAddress ip, int port)
{
Ip = ip;
Port = port;
Start();
}
public virtual void Stop()
{
listener.Stop();
@ -104,9 +108,12 @@ namespace Rests
var obj = ExecuteCommand(com, verbs, e.Request.Parameters);
if (obj != null)
return obj;
}
return new Dictionary<string, string> { { "status", "404" }, { "error", "Specified API endpoint doesn't exist. Refer to the documentation for a list of valid endpoints." } };
return new Dictionary<string, string>
{
{"status", "404"},
{"error", "Specified API endpoint doesn't exist. Refer to the documentation for a list of valid endpoints."}
};
}
protected virtual object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms)
@ -115,11 +122,13 @@ namespace Rests
}
#region Dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
@ -131,6 +140,7 @@ namespace Rests
}
}
}
~Rest()
{
Dispose(false);

View file

@ -28,6 +28,7 @@ namespace Rests
Callback = callback;
RequiresToken = true;
}
/// <summary>
///
/// </summary>
@ -36,7 +37,6 @@ namespace Rests
public RestCommand(string uritemplate, RestCommandD callback)
: this(string.Empty, uritemplate, callback)
{
}
public bool HasVerbs

View file

@ -8,10 +8,10 @@ using TShockAPI.DB;
namespace TShockAPI
{
public class RestManager
{
private Rest Rest;
public RestManager(Rest rest)
{
Rest = rest;
@ -45,12 +45,13 @@ namespace TShockAPI
#region RestMethods
object TokenTest(RestVerbs verbs, IParameterCollection parameters)
private object TokenTest(RestVerbs verbs, IParameterCollection parameters)
{
return new Dictionary<string, string> { { "status", "200" }, { "response", "Token is valid and was passed through correctly." } };
return new Dictionary<string, string>
{{"status", "200"}, {"response", "Token is valid and was passed through correctly."}};
}
object Status(RestVerbs verbs, IParameterCollection parameters)
private object Status(RestVerbs verbs, IParameterCollection parameters)
{
if (TShock.Config.EnableTokenEndpointAuthentication)
return new RestObject("403") {Error = "Server settings require a token for this API call."};
@ -71,7 +72,7 @@ namespace TShockAPI
#region RestUserMethods
object UserList(RestVerbs verbs, IParameterCollection parameters)
private object UserList(RestVerbs verbs, IParameterCollection parameters)
{
var activeplayers = Main.player.Where(p => p != null && p.active).ToList();
string currentPlayers = string.Join(", ", activeplayers.Select(p => p.name));
@ -80,7 +81,7 @@ namespace TShockAPI
return ret;
}
object UserUpdate(RestVerbs verbs, IParameterCollection parameters)
private object UserUpdate(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, string>();
var password = parameters["password"];
@ -117,7 +118,7 @@ namespace TShockAPI
return returnBlock;
}
object UserDestroy(RestVerbs verbs, IParameterCollection parameters)
private object UserDestroy(RestVerbs verbs, IParameterCollection parameters)
{
var user = TShock.Users.GetUserByName(verbs["user"]);
if (user == null)
@ -140,7 +141,7 @@ namespace TShockAPI
return returnBlock;
}
object UserInfo(RestVerbs verbs, IParameterCollection parameters)
private object UserInfo(RestVerbs verbs, IParameterCollection parameters)
{
var user = TShock.Users.GetUserByName(verbs["user"]);
if (user == null)
@ -159,7 +160,7 @@ namespace TShockAPI
#region RestBanMethods
object BanCreate(RestVerbs verbs, IParameterCollection parameters)
private object BanCreate(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, string>();
var ip = parameters["ip"];
@ -203,7 +204,7 @@ namespace TShockAPI
return returnBlock;
}
object BanDestroy(RestVerbs verbs, IParameterCollection parameters)
private object BanDestroy(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, string>();
@ -243,7 +244,7 @@ namespace TShockAPI
return returnBlock;
}
object BanInfo(RestVerbs verbs, IParameterCollection parameters)
private object BanInfo(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, string>();
@ -278,7 +279,8 @@ namespace TShockAPI
#endregion
#region RestWorldMethods
object WorldRead(RestVerbs verbs, IParameterCollection parameters)
private object WorldRead(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, object>();
returnBlock.Add("status", "200");
@ -291,7 +293,7 @@ namespace TShockAPI
return returnBlock;
}
object WorldMeteor(RestVerbs verbs, IParameterCollection parameters)
private object WorldMeteor(RestVerbs verbs, IParameterCollection parameters)
{
WorldGen.dropMeteor();
var returnBlock = new Dictionary<string, string>();
@ -300,7 +302,7 @@ namespace TShockAPI
return returnBlock;
}
object WorldBloodmoon(RestVerbs verbs, IParameterCollection parameters)
private object WorldBloodmoon(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, string>();
var bloodmoonVerb = verbs["bool"];
@ -322,10 +324,12 @@ namespace TShockAPI
returnBlock.Add("response", "Blood Moon has been set to " + bloodmoon);
return returnBlock;
}
#endregion
#region RestPlayerMethods
object PlayerRead(RestVerbs verbs, IParameterCollection parameters)
private object PlayerRead(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, object>();
var playerParam = parameters["player"];
@ -355,7 +359,8 @@ namespace TShockAPI
}
return returnBlock;
}
object PlayerKick(RestVerbs verbs, IParameterCollection parameters)
private object PlayerKick(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, object>();
var playerParam = parameters["player"];
@ -380,7 +385,8 @@ namespace TShockAPI
}
return returnBlock;
}
object PlayerBan(RestVerbs verbs, IParameterCollection parameters)
private object PlayerBan(RestVerbs verbs, IParameterCollection parameters)
{
var returnBlock = new Dictionary<string, object>();
var playerParam = parameters["player"];
@ -406,6 +412,7 @@ namespace TShockAPI
}
return returnBlock;
}
#endregion
#region RestExampleMethods
@ -417,17 +424,19 @@ namespace TShockAPI
}
//The Wizard example, for demonstrating the response convention:
object Wizard(RestVerbs verbs, IParameterCollection parameters)
private object Wizard(RestVerbs verbs, IParameterCollection parameters)
{
var returnBack = new Dictionary<string, string>();
returnBack.Add("status", "200"); //Keep this in everything, 200 = ok, etc. Standard http status codes.
returnBack.Add("error", "(If this failed, you would have a different status code and provide the error object.)"); //And only include this if the status isn't 200 or a failure
returnBack.Add("Verified Wizard", "You're a wizard, " + verbs["username"]); //Outline any api calls and possible responses in some form of documentation somewhere
returnBack.Add("error", "(If this failed, you would have a different status code and provide the error object.)");
//And only include this if the status isn't 200 or a failure
returnBack.Add("Verified Wizard", "You're a wizard, " + verbs["username"]);
//Outline any api calls and possible responses in some form of documentation somewhere
return returnBack;
}
//http://127.0.0.1:8080/HelloWorld/name/{username}?type=status
object UserTest(RestVerbs verbs, IParameterCollection parameters)
private object UserTest(RestVerbs verbs, IParameterCollection parameters)
{
var ret = new Dictionary<string, string>();
var type = parameters["type"];
@ -443,6 +452,7 @@ namespace TShockAPI
}
return null;
}
#endregion
}
}

View file

@ -11,11 +11,13 @@ namespace Rests
get { return this["status"] as string; }
set { this["status"] = value; }
}
public string Error
{
get { return this["error"] as string; }
set { this["error"] = value; }
}
public string Response
{
get { return this["response"] as string; }

View file

@ -13,10 +13,12 @@ namespace Rests
/// <param name="password">Password to verify</param>
/// <returns>Returning a restobject with a null error means a successful verification.</returns>
public delegate RestObject VerifyD(string username, string password);
public class SecureRest : Rest
{
public Dictionary<string, object> Tokens { get; protected set; }
public event VerifyD Verify;
public SecureRest(IPAddress ip, int port)
: base(ip, port)
{
@ -25,7 +27,7 @@ namespace Rests
Register(new RestCommand("/token/destroy/{token}", DestroyToken) {RequiresToken = true});
}
object DestroyToken(RestVerbs verbs, IParameterCollection parameters)
private object DestroyToken(RestVerbs verbs, IParameterCollection parameters)
{
var token = verbs["token"];
try
@ -34,12 +36,14 @@ namespace Rests
}
catch (Exception)
{
return new Dictionary<string, string> { { "status", "400" }, { "error", "The specified token queued for destruction failed to be deleted." } };
return new Dictionary<string, string>
{{"status", "400"}, {"error", "The specified token queued for destruction failed to be deleted."}};
}
return new Dictionary<string, string> { { "status", "200" }, { "response", "Requested token was successfully destroyed." } };
return new Dictionary<string, string>
{{"status", "200"}, {"response", "Requested token was successfully destroyed."}};
}
object NewToken(RestVerbs verbs, IParameterCollection parameters)
private object NewToken(RestVerbs verbs, IParameterCollection parameters)
{
var user = verbs["username"];
var pass = verbs["password"];
@ -49,7 +53,8 @@ namespace Rests
obj = Verify(user, pass);
if (obj == null)
obj = new RestObject("401") { Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair." };
obj = new RestObject("401")
{Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair."};
if (obj.Error != null)
return obj;
@ -70,18 +75,25 @@ namespace Rests
}
protected override object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms)
{
if (cmd.RequiresToken)
{
var strtoken = parms["token"];
if (strtoken == null)
return new Dictionary<string, string> { { "status", "401" }, { "error", "Not authorized. The specified API endpoint requires a token." } };
return new Dictionary<string, string>
{{"status", "401"}, {"error", "Not authorized. The specified API endpoint requires a token."}};
object token;
if (!Tokens.TryGetValue(strtoken, out token))
return new Dictionary<string, string> { { "status", "403" }, { "error", "Not authorized. The specified API endpoint requires a token, but the provided token was not valid." } };
return new Dictionary<string, string>
{
{"status", "403"},
{
"error",
"Not authorized. The specified API endpoint requires a token, but the provided token was not valid."
}
};
}
return base.ExecuteCommand(cmd, verbs, parms);
}

View file

@ -8,9 +8,9 @@ namespace TShockAPI
{
public class StatTracker
{
Utils Utils = TShock.Utils;
private Utils Utils = TShock.Utils;
public DateTime lastcheck = DateTime.MinValue;
readonly int checkinFrequency = 5;
private readonly int checkinFrequency = 5;
public void checkin()
{
@ -57,11 +57,17 @@ namespace TShockAPI
string response;
if (TShock.Config.DisablePlayerCountReporting)
{
response = client.DownloadString("http://tshock.co/tickto.php?do=log&fp=" + fp + "&ver=" + TShock.VersionNum + "&os=" + Environment.OSVersion + "&mono=" + Main.runningMono + "&port=" + Netplay.serverPort + "&plcount=0");
response =
client.DownloadString("http://tshock.co/tickto.php?do=log&fp=" + fp + "&ver=" + TShock.VersionNum + "&os=" +
Environment.OSVersion + "&mono=" + Main.runningMono + "&port=" + Netplay.serverPort +
"&plcount=0");
}
else
{
response = client.DownloadString("http://tshock.co/tickto.php?do=log&fp=" + fp + "&ver=" + TShock.VersionNum + "&os=" + Environment.OSVersion + "&mono=" + Main.runningMono + "&port=" + Netplay.serverPort + "&plcount=" + TShock.Utils.ActivePlayers());
response =
client.DownloadString("http://tshock.co/tickto.php?do=log&fp=" + fp + "&ver=" + TShock.VersionNum + "&os=" +
Environment.OSVersion + "&mono=" + Main.runningMono + "&port=" + Netplay.serverPort +
"&plcount=" + TShock.Utils.ActivePlayers());
}
Log.ConsoleInfo("Stat Tracker: " + response + "\n");
}

View file

@ -61,7 +61,7 @@ namespace TShockAPI
public bool TPAllow = true;
public bool mute;
public bool TpLock;
Player FakePlayer;
private Player FakePlayer;
public bool RequestedSection;
public DateTime LastDeath { get; set; }
public bool Dead;
@ -79,9 +79,14 @@ namespace TShockAPI
{
get { return Index >= 0 && Index < Main.maxNetPlayers && Main.player[Index] != null; }
}
public bool ConnectionAlive
{
get { return RealPlayer && (Netplay.serverSock[Index] != null && Netplay.serverSock[Index].active && !Netplay.serverSock[Index].kill); }
get
{
return RealPlayer &&
(Netplay.serverSock[Index] != null && Netplay.serverSock[Index].active && !Netplay.serverSock[Index].kill);
}
}
public int State
@ -95,56 +100,61 @@ namespace TShockAPI
get
{
if (string.IsNullOrEmpty(CacheIP))
return CacheIP = RealPlayer ? (Netplay.serverSock[Index].tcpClient.Connected ? TShock.Utils.GetRealIP(Netplay.serverSock[Index].tcpClient.Client.RemoteEndPoint.ToString()) : "") : "";
return
CacheIP =
RealPlayer
? (Netplay.serverSock[Index].tcpClient.Connected
? TShock.Utils.GetRealIP(Netplay.serverSock[Index].tcpClient.Client.RemoteEndPoint.ToString())
: "")
: "";
else
return CacheIP;
}
}
/// <summary>
/// Terraria Player
/// </summary>
public Player TPlayer
{
get
{
return FakePlayer ?? Main.player[Index];
}
get { return FakePlayer ?? Main.player[Index]; }
}
public string Name
{
get { return TPlayer.name; }
}
public bool Active
{
get { return TPlayer != null && TPlayer.active; }
}
public int Team
{
get { return TPlayer.team; }
}
public float X
{
get
{
get { return RealPlayer ? TPlayer.position.X : Main.spawnTileX*16; }
}
return RealPlayer ? TPlayer.position.X : Main.spawnTileX * 16;
}
}
public float Y
{
get
{
return RealPlayer ? TPlayer.position.Y : Main.spawnTileY * 16;
}
get { return RealPlayer ? TPlayer.position.Y : Main.spawnTileY*16; }
}
public int TileX
{
get { return (int) (X/16); }
}
public int TileY
{
get { return (int) (Y/16); }
}
public bool InventorySlotAvailable
{
get
@ -197,7 +207,7 @@ namespace TShockAPI
}
void SendWorldInfo(int tilex, int tiley, bool fakeid)
private void SendWorldInfo(int tilex, int tiley, bool fakeid)
{
using (var ms = new MemoryStream())
{
@ -311,7 +321,8 @@ namespace TShockAPI
// This is for special pickaxe/hammers/swords etc
Main.item[itemid].SetDefaults(name);
// The set default overrides the wet and stack set by NewItem
Main.item[itemid].wet = Collision.WetCollision(Main.item[itemid].position, Main.item[itemid].width, Main.item[itemid].height);
Main.item[itemid].wet = Collision.WetCollision(Main.item[itemid].position, Main.item[itemid].width,
Main.item[itemid].height);
Main.item[itemid].stack = stack;
Main.item[itemid].owner = Index;
Main.item[itemid].prefix = (byte) prefix;
@ -336,7 +347,8 @@ namespace TShockAPI
public virtual void DamagePlayer(int damage)
{
NetMessage.SendData((int)PacketTypes.PlayerDamage, -1, -1, "", Index, ((new Random()).Next(-1, 1)), damage, (float)0);
NetMessage.SendData((int) PacketTypes.PlayerDamage, -1, -1, "", Index, ((new Random()).Next(-1, 1)), damage,
(float) 0);
}
public virtual void SetTeam(int team)
@ -375,7 +387,8 @@ namespace TShockAPI
}
//Todo: Separate this into a few functions. SendTo, SendToAll, etc
public virtual void SendData(PacketTypes msgType, string text = "", int number = 0, float number2 = 0f, float number3 = 0f, float number4 = 0f, int number5 = 0)
public virtual void SendData(PacketTypes msgType, string text = "", int number = 0, float number2 = 0f,
float number3 = 0f, float number4 = 0f, int number5 = 0)
{
if (RealPlayer && !ConnectionAlive)
return;
@ -436,13 +449,15 @@ namespace TShockAPI
NetMessage.syncPlayers();
}
public void SpawnNPC(int type, string name, int amount, int startTileX, int startTileY, int tileXRange = 100, int tileYRange = 50)
public void SpawnNPC(int type, string name, int amount, int startTileX, int startTileY, int tileXRange = 100,
int tileYRange = 50)
{
for (int i = 0; i < amount; i++)
{
int spawnTileX;
int spawnTileY;
TShock.Utils.GetRandomClearTileWithInRange(startTileX, startTileY, tileXRange, tileYRange, out spawnTileX, out spawnTileY);
TShock.Utils.GetRandomClearTileWithInRange(startTileX, startTileY, tileXRange, tileYRange, out spawnTileX,
out spawnTileY);
int npcid = NPC.NewNPC(spawnTileX*16, spawnTileY*16, type, 0);
// This is for special slimes
Main.npc[npcid].SetDefaults(name);

View file

@ -48,7 +48,7 @@ namespace TShockAPI
public class TShock : TerrariaPlugin
{
public static readonly Version VersionNum = Assembly.GetExecutingAssembly().GetName().Version;
public static readonly string VersionCodename = "Zidonuke fixin' what Redigit doesn't";
public static readonly string VersionCodename = "This code is a mess";
public static string SavePath = "tshock";
@ -71,6 +71,7 @@ namespace TShockAPI
public static RestManager RestManager;
public static Utils Utils = new Utils();
public static StatTracker StatTracker = new StatTracker();
/// <summary>
/// Called after TShock is initialized. Useful for plugins that needs hooks before tshock but also depend on tshock being loaded.
/// </summary>
@ -105,7 +106,6 @@ namespace TShockAPI
}
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public override void Initialize()
{
@ -125,7 +125,8 @@ namespace TShockAPI
{
if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
{
Log.ConsoleInfo("TShock was improperly shut down. Please avoid this in the future, world corruption may result from this.");
Log.ConsoleInfo(
"TShock was improperly shut down. Please avoid this in the future, world corruption may result from this.");
File.Delete(Path.Combine(SavePath, "tshock.pid"));
}
File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString());
@ -224,27 +225,31 @@ namespace TShockAPI
Log.Error(ex.ToString());
Environment.Exit(1);
}
}
RestObject RestApi_Verify(string username, string password)
private RestObject RestApi_Verify(string username, string password)
{
var userAccount = Users.GetUserByName(username);
if (userAccount == null)
{
return new RestObject("401") { Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair." };
return new RestObject("401")
{Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair."};
}
if (Utils.HashPassword(password).ToUpper() != userAccount.Password.ToUpper())
{
return new RestObject("401") { Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair." };
return new RestObject("401")
{Error = "Invalid username/password combination provided. Please re-submit your query with a correct pair."};
}
if (!Utils.GetGroup(userAccount.Group).HasPermission("api") && userAccount.Group != "superadmin")
{
return new RestObject("403") { Error = "Although your account was successfully found and identified, your account lacks the permission required to use the API. (api)" };
return new RestObject("403")
{
Error =
"Although your account was successfully found and identified, your account lacks the permission required to use the API. (api)"
};
}
return new RestObject("200") {Response = "Successful login"}; //Maybe return some user info too?
@ -400,7 +405,8 @@ namespace TShockAPI
AuthToken = Convert.ToInt32(tr.ReadLine());
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("TShock Notice: authcode.txt is still present, and the AuthToken located in that file will be used.");
Console.WriteLine(
"TShock Notice: authcode.txt is still present, and the AuthToken located in that file will be used.");
Console.WriteLine("To become superadmin, join the game and type /auth " + AuthToken);
Console.WriteLine("This token will display until disabled by verification. (/auth-verify)");
Console.ForegroundColor = ConsoleColor.Gray;
@ -416,7 +422,6 @@ namespace TShockAPI
StatTracker.checkin();
FixChestStacks();
}
private void FixChestStacks()
@ -535,7 +540,8 @@ namespace TShockAPI
string check = "none";
foreach (Item item in player.TPlayer.inventory)
{
if (!player.Group.HasPermission(Permissions.ignorestackhackdetection) && item.stack > item.maxStack && item.type != 0)
if (!player.Group.HasPermission(Permissions.ignorestackhackdetection) && item.stack > item.maxStack &&
item.type != 0)
{
check = "Remove Item " + item.name + " (" + item.stack + ") exceeds max stack of " + item.maxStack;
}
@ -558,13 +564,15 @@ namespace TShockAPI
player.SetBuff(32, 120); //Slow
player.SetBuff(23, 120); //Cursed
}
else if(!player.Group.HasPermission(Permissions.usebanneditem) && Itembans.ItemIsBanned(player.TPlayer.inventory[player.TPlayer.selectedItem].name, player))
else if (!player.Group.HasPermission(Permissions.usebanneditem) &&
Itembans.ItemIsBanned(player.TPlayer.inventory[player.TPlayer.selectedItem].name, player))
{
player.SetBuff(23, 120); //Cursed
}
}
}
Console.Title = string.Format("TerrariaShock Version {0} ({1}) ({2}/{3})", Version, VersionCodename, count, Config.MaxSlots);
Console.Title = string.Format("TerrariaShock Version {0} ({1}) ({2}/{3})", Version, VersionCodename, count,
Config.MaxSlots);
}
private void OnConnect(int ply, HandledEventArgs handler)
@ -699,7 +707,9 @@ namespace TShockAPI
}
else if (!tsplr.mute)
{
Utils.Broadcast(String.Format(Config.ChatFormat, tsplr.Group.Name, tsplr.Group.Prefix, tsplr.Name, tsplr.Group.Suffix, text), tsplr.Group.R, tsplr.Group.G, tsplr.Group.B);
Utils.Broadcast(
String.Format(Config.ChatFormat, tsplr.Group.Name, tsplr.Group.Prefix, tsplr.Name, tsplr.Group.Suffix, text),
tsplr.Group.R, tsplr.Group.G, tsplr.Group.B);
e.Handled = true;
}
else if (tsplr.mute)
@ -787,7 +797,8 @@ namespace TShockAPI
return;
}
if ((player.State < 10 || player.Dead) && (int)type > 12 && (int)type != 16 && (int)type != 42 && (int)type != 50 && (int)type != 38)
if ((player.State < 10 || player.Dead) && (int) type > 12 && (int) type != 16 && (int) type != 42 && (int) type != 50 &&
(int) type != 38)
{
e.Handled = true;
return;
@ -827,7 +838,9 @@ namespace TShockAPI
{
if (Config.ServerSideInventory)
{
player.SendMessage(player.IgnoreActionsForInventory = "Server Side Inventory is enabled! Please /register or /login to play!", Color.Red);
player.SendMessage(
player.IgnoreActionsForInventory = "Server Side Inventory is enabled! Please /register or /login to play!",
Color.Red);
}
else if (Config.RequireLogin)
{
@ -864,7 +877,7 @@ namespace TShockAPI
}
}
void OnProjectileSetDefaults(SetDefaultsEventArgs<Projectile, int> e)
private void OnProjectileSetDefaults(SetDefaultsEventArgs<Projectile, int> e)
{
if (e.Info == 43)
if (Config.DisableTombstones)
@ -875,10 +888,9 @@ namespace TShockAPI
if (e.Info == 109)
if (Config.DisableSnowBalls)
e.Object.SetDefaults(0);
}
void OnNpcSetDefaults(SetDefaultsEventArgs<NPC, int> e)
private void OnNpcSetDefaults(SetDefaultsEventArgs<NPC, int> e)
{
if (Itembans.ItemIsBanned(e.Object.name, null))
{
@ -902,6 +914,7 @@ namespace TShockAPI
return SendBytesBufferless(client, bytes);
}
/// <summary>
/// Send bytes to a client ignoring the packet buffer
/// </summary>
@ -924,7 +937,7 @@ namespace TShockAPI
return false;
}
void NetHooks_SendData(SendDataEventArgs e)
private void NetHooks_SendData(SendDataEventArgs e)
{
if (e.MsgID == PacketTypes.Disconnect)
{
@ -966,7 +979,7 @@ namespace TShockAPI
e.Handled = true;
}
void OnStartHardMode(HandledEventArgs e)
private void OnStartHardMode(HandledEventArgs e)
{
if (Config.DisableHardmode)
e.Handled = true;
@ -1039,12 +1052,14 @@ namespace TShockAPI
return true;
}
if (type == 17 && !player.Group.HasPermission(Permissions.usebanneditem) && Itembans.ItemIsBanned("Dirt Rod", player)) //Dirt Rod Projectile
if (type == 17 && !player.Group.HasPermission(Permissions.usebanneditem) && Itembans.ItemIsBanned("Dirt Rod", player))
//Dirt Rod Projectile
{
return true;
}
if ((type == 42 || type == 65 || type == 68) && !player.Group.HasPermission(Permissions.usebanneditem) && Itembans.ItemIsBanned("Sandgun", player)) //Sandgun Projectiles
if ((type == 42 || type == 65 || type == 68) && !player.Group.HasPermission(Permissions.usebanneditem) &&
Itembans.ItemIsBanned("Sandgun", player)) //Sandgun Projectiles
{
return true;
}
@ -1081,7 +1096,8 @@ namespace TShockAPI
player.SendMessage("You do not have permission to build!", Color.Red);
return true;
}
if (!player.Group.HasPermission(Permissions.editspawn) && !Regions.CanBuild(tileX, tileY, player) && Regions.InArea(tileX, tileY))
if (!player.Group.HasPermission(Permissions.editspawn) && !Regions.CanBuild(tileX, tileY, player) &&
Regions.InArea(tileX, tileY))
{
player.SendMessage("Region protected from changes.", Color.Red);
return true;
@ -1115,6 +1131,7 @@ namespace TShockAPI
Vector2 spawn = new Vector2(Main.spawnTileX, Main.spawnTileY);
return Distance(spawn, tile) <= Config.SpawnProtectionRadius;
}
public static float Distance(Vector2 value1, Vector2 value2)
{
float num2 = value1.X - value2.X;
@ -1150,7 +1167,9 @@ namespace TShockAPI
if (inventory[i].stack > item.maxStack)
{
check = true;
player.SendMessage(String.Format("Stack cheat detected. Remove item {0} ({1}) and then rejoin", item.name, inventory[i].stack), Color.Cyan);
player.SendMessage(
String.Format("Stack cheat detected. Remove item {0} ({1}) and then rejoin", item.name, inventory[i].stack),
Color.Cyan);
}
}
}
@ -1165,7 +1184,9 @@ namespace TShockAPI
if (armor[i - 48].stack > item.maxStack)
{
check = true;
player.SendMessage(String.Format("Stack cheat detected. Remove armor {0} ({1}) and then rejoin", item.name, armor[i - 48].stack), Color.Cyan);
player.SendMessage(
String.Format("Stack cheat detected. Remove armor {0} ({1}) and then rejoin", item.name, armor[i - 48].stack),
Color.Cyan);
}
}
}
@ -1181,7 +1202,8 @@ namespace TShockAPI
if (player.TPlayer.statLifeMax > playerData.maxHealth)
{
player.SendMessage("Error: Your max health exceeded (" + playerData.maxHealth + ") which is stored on server", Color.Cyan);
player.SendMessage("Error: Your max health exceeded (" + playerData.maxHealth + ") which is stored on server",
Color.Cyan);
check = false;
}
@ -1200,7 +1222,8 @@ namespace TShockAPI
item.netDefaults(inventory[i].netID);
item.Prefix(inventory[i].prefix);
item.AffixName();
player.SendMessage(player.IgnoreActionsForInventory = "Your item (" + item.name + ") needs to be deleted.", Color.Cyan);
player.SendMessage(player.IgnoreActionsForInventory = "Your item (" + item.name + ") needs to be deleted.",
Color.Cyan);
check = false;
}
else if (playerData.inventory[i].prefix != inventory[i].prefix)
@ -1208,7 +1231,8 @@ namespace TShockAPI
item.netDefaults(inventory[i].netID);
item.Prefix(inventory[i].prefix);
item.AffixName();
player.SendMessage(player.IgnoreActionsForInventory = "Your item (" + item.name + ") needs to be deleted.", Color.Cyan);
player.SendMessage(player.IgnoreActionsForInventory = "Your item (" + item.name + ") needs to be deleted.",
Color.Cyan);
check = false;
}
else if (inventory[i].stack > playerData.inventory[i].stack)
@ -1216,7 +1240,10 @@ namespace TShockAPI
item.netDefaults(inventory[i].netID);
item.Prefix(inventory[i].prefix);
item.AffixName();
player.SendMessage(player.IgnoreActionsForInventory = "Your item (" + item.name + ") (" + inventory[i].stack + ") needs to have it's stack decreased to (" + playerData.inventory[i].stack + ").", Color.Cyan);
player.SendMessage(
player.IgnoreActionsForInventory =
"Your item (" + item.name + ") (" + inventory[i].stack + ") needs to have it's stack decreased to (" +
playerData.inventory[i].stack + ").", Color.Cyan);
check = false;
}
}
@ -1232,7 +1259,8 @@ namespace TShockAPI
item.netDefaults(armor[i - 48].netID);
item.Prefix(armor[i - 48].prefix);
item.AffixName();
player.SendMessage(player.IgnoreActionsForInventory = "Your armor (" + item.name + ") needs to be deleted.", Color.Cyan);
player.SendMessage(player.IgnoreActionsForInventory = "Your armor (" + item.name + ") needs to be deleted.",
Color.Cyan);
check = false;
}
else if (playerData.inventory[i].prefix != armor[i - 48].prefix)
@ -1240,7 +1268,8 @@ namespace TShockAPI
item.netDefaults(armor[i - 48].netID);
item.Prefix(armor[i - 48].prefix);
item.AffixName();
player.SendMessage(player.IgnoreActionsForInventory = "Your armor (" + item.name + ") needs to be deleted.", Color.Cyan);
player.SendMessage(player.IgnoreActionsForInventory = "Your armor (" + item.name + ") needs to be deleted.",
Color.Cyan);
check = false;
}
else if (armor[i - 48].stack > playerData.inventory[i].stack)
@ -1248,7 +1277,10 @@ namespace TShockAPI
item.netDefaults(armor[i - 48].netID);
item.Prefix(armor[i - 48].prefix);
item.AffixName();
player.SendMessage(player.IgnoreActionsForInventory = "Your armor (" + item.name + ") (" + inventory[i].stack + ") needs to have it's stack decreased to (" + playerData.inventory[i].stack + ").", Color.Cyan);
player.SendMessage(
player.IgnoreActionsForInventory =
"Your armor (" + item.name + ") (" + inventory[i].stack + ") needs to have it's stack decreased to (" +
playerData.inventory[i].stack + ").", Color.Cyan);
check = false;
}
}

View file

@ -24,14 +24,15 @@ using Newtonsoft.Json;
namespace TShockAPI
{
class UpdateManager
internal class UpdateManager
{
static string updateUrl = "http://shankshock.com/tshock-update.json";
private static string updateUrl = "http://shankshock.com/tshock-update.json";
public static DateTime lastcheck = DateTime.MinValue;
/// <summary>
/// Check once every X minutes.
/// </summary>
static readonly int CheckXMinutes = 30;
private static readonly int CheckXMinutes = 30;
public static void UpdateProcedureCheck()
{

View file

@ -144,7 +144,8 @@ namespace TShockAPI
TSPlayer.Server.SendMessage(log, color);
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active && player.Group.HasPermission(Permissions.logs) && player.DisplayLogs && TShock.Config.DisableSpewLogs == false)
if (player != null && player.Active && player.Group.HasPermission(Permissions.logs) && player.DisplayLogs &&
TShock.Config.DisableSpewLogs == false)
player.SendMessage(log, color);
}
}
@ -189,7 +190,8 @@ namespace TShockAPI
return found;
}
public void GetRandomClearTileWithInRange(int startTileX, int startTileY, int tileXRange, int tileYRange, out int tileX, out int tileY)
public void GetRandomClearTileWithInRange(int startTileX, int startTileY, int tileXRange, int tileYRange,
out int tileX, out int tileY)
{
int j = 0;
do
@ -204,8 +206,7 @@ namespace TShockAPI
tileX = startTileX + Random.Next(tileXRange*-1, tileXRange);
tileY = startTileY + Random.Next(tileYRange*-1, tileYRange);
j++;
}
while (TileValid(tileX, tileY) && !TileClear(tileX, tileY));
} while (TileValid(tileX, tileY) && !TileClear(tileX, tileY));
}
private bool TileValid(int tileX, int tileY)
@ -258,7 +259,9 @@ namespace TShockAPI
if (item.name.ToLower().StartsWith(name.ToLower()))
found.Add(item);
}
catch { }
catch
{
}
}
return found;
}
@ -360,7 +363,9 @@ namespace TShockAPI
if (item.AffixName().Trim().ToLower().StartsWith(name.ToLower()))
found.Add(i);
}
catch { }
catch
{
}
}
return found;
}
@ -561,6 +566,7 @@ namespace TShockAPI
return ret.Aggregate("", (s, b) => s + b.ToString("X2"));
}
}
/// <summary>
/// Returns a Sha256 string for a given string
/// </summary>