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

View file

@ -31,10 +31,12 @@ using TShockAPI.DB;
namespace TShockAPI namespace TShockAPI
{ {
public delegate void CommandDelegate(CommandArgs args); public delegate void CommandDelegate(CommandArgs args);
public class CommandArgs : EventArgs public class CommandArgs : EventArgs
{ {
public string Message { get; private set; } public string Message { get; private set; }
public TSPlayer Player { get; private set; } public TSPlayer Player { get; private set; }
/// <summary> /// <summary>
/// Parameters passed to the arguement. Does not include the command name. /// Parameters passed to the arguement. Does not include the command name.
/// IE '/kick "jerk face"' will only have 1 argument /// IE '/kick "jerk face"' will only have 1 argument
@ -53,9 +55,14 @@ namespace TShockAPI
Parameters = args; Parameters = args;
} }
} }
public class Command 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 List<string> Names { get; protected set; }
public bool DoLog { get; set; } public bool DoLog { get; set; }
public string Permission { get; protected set; } public string Permission { get; protected set; }
@ -66,6 +73,7 @@ namespace TShockAPI
{ {
Permission = permissionneeded; Permission = permissionneeded;
} }
public Command(CommandDelegate cmd, params string[] names) public Command(CommandDelegate cmd, params string[] names)
{ {
if (names == null || names.Length < 1) if (names == null || names.Length < 1)
@ -104,11 +112,13 @@ namespace TShockAPI
return ply.Group.HasPermission(Permission); return ply.Group.HasPermission(Permission);
} }
} }
public static class Commands public static class Commands
{ {
public static List<Command> ChatCommands = new List<Command>(); 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() public static void InitCommands()
{ {
//When adding new perm in here, add new perm to CommandList in DBEditor //When adding new perm in here, add new perm to CommandList in DBEditor
@ -175,12 +185,12 @@ namespace TShockAPI
add(null, Rules, "rules"); add(null, Rules, "rules");
add(Permissions.mute, Mute, "mute", "unmute"); add(Permissions.mute, Mute, "mute", "unmute");
add(Permissions.logs, DisplayLogs, "displaylogs"); add(Permissions.logs, DisplayLogs, "displaylogs");
ChatCommands.Add(new Command(Permissions.canchangepassword, PasswordUser, "password") { DoLog = false }); ChatCommands.Add(new Command(Permissions.canchangepassword, PasswordUser, "password") {DoLog = false});
ChatCommands.Add(new Command(Permissions.canregister, RegisterUser, "register") { DoLog = false }); ChatCommands.Add(new Command(Permissions.canregister, RegisterUser, "register") {DoLog = false});
ChatCommands.Add(new Command(Permissions.rootonly, ManageUsers, "user") { DoLog = false }); ChatCommands.Add(new Command(Permissions.rootonly, ManageUsers, "user") {DoLog = false});
add(Permissions.rootonly, GrabUserUserInfo, "userinfo", "ui"); add(Permissions.rootonly, GrabUserUserInfo, "userinfo", "ui");
add(Permissions.rootonly, AuthVerify, "auth-verify"); add(Permissions.rootonly, AuthVerify, "auth-verify");
ChatCommands.Add(new Command(Permissions.canlogin, AttemptLogin, "login") { DoLog = false }); ChatCommands.Add(new Command(Permissions.canlogin, AttemptLogin, "login") {DoLog = false});
add(Permissions.cfg, Broadcast, "broadcast", "bc"); add(Permissions.cfg, Broadcast, "broadcast", "bc");
add(Permissions.whisper, Whisper, "whisper", "w", "tell"); add(Permissions.whisper, Whisper, "whisper", "w", "tell");
add(Permissions.whisper, Reply, "reply", "r"); add(Permissions.whisper, Reply, "reply", "r");
@ -321,10 +331,10 @@ namespace TShockAPI
public static void AttemptLogin(CommandArgs args) public static void AttemptLogin(CommandArgs args)
{ {
if (args.Player.LoginAttempts > TShock.Config.MaximumLoginAttempts && (TShock.Config.MaximumLoginAttempts != -1)) 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."); 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); args.Player.SendMessage("There was an error processing your request.", Color.Red);
Log.Error(ex.ToString()); Log.Error(ex.ToString());
} }
} }
private static void PasswordUser(CommandArgs args) private static void PasswordUser(CommandArgs args)
@ -410,12 +419,14 @@ namespace TShockAPI
else else
{ {
args.Player.SendMessage("You failed to change your password!", Color.Red); 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 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) catch (UserManagerException ex)
@ -567,7 +578,6 @@ namespace TShockAPI
try try
{ {
if (args.Parameters.Count == 3) if (args.Parameters.Count == 3)
{ {
args.Player.SendMessage("Changed the password of " + user.Name + "!", Color.Green); args.Player.SendMessage("Changed the password of " + user.Name + "!", Color.Green);
@ -596,18 +606,19 @@ namespace TShockAPI
try try
{ {
if (args.Parameters.Count == 3) if (args.Parameters.Count == 3)
{ {
if (!string.IsNullOrEmpty(user.Address)) 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]); TShock.Users.SetUserGroup(user, args.Parameters[2]);
Log.ConsoleInfo(args.Player.Name + " changed IP Address " + user.Address + " to group " + args.Parameters[2]); Log.ConsoleInfo(args.Player.Name + " changed IP Address " + user.Address + " to group " + args.Parameters[2]);
} }
else 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]); TShock.Users.SetUserGroup(user, args.Parameters[2]);
Log.ConsoleInfo(args.Player.Name + " changed Account " + user.Name + " to group " + 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); args.Player.SendMessage("Invalid user syntax. Try /user help.", Color.Red);
} }
} }
#endregion #endregion
#region Stupid commands #region Stupid commands
public static void ServerInfo(CommandArgs args) public static void ServerInfo(CommandArgs args)
{ {
args.Player.SendMessage("Memory usage: " + Process.GetCurrentProcess().WorkingSet64); args.Player.SendMessage("Memory usage: " + Process.GetCurrentProcess().WorkingSet64);
@ -648,6 +661,7 @@ namespace TShockAPI
args.Player.SendMessage("Proc count: " + Environment.ProcessorCount); args.Player.SendMessage("Proc count: " + Environment.ProcessorCount);
args.Player.SendMessage("Machine name: " + Environment.MachineName); args.Player.SendMessage("Machine name: " + Environment.MachineName);
} }
#endregion #endregion
#region Player Management Commands #region Player Management Commands
@ -701,7 +715,9 @@ namespace TShockAPI
} }
else 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)) if (!TShock.Utils.Kick(players[0], reason))
{ {
args.Player.SendMessage("You can't kick another admin!", Color.Red); args.Player.SendMessage("You can't kick another admin!", Color.Red);
@ -734,7 +750,9 @@ namespace TShockAPI
} }
else 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)) if (!TShock.Utils.Ban(players[0], reason))
{ {
args.Player.SendMessage("You can't ban another admin!", Color.Red); args.Player.SendMessage("You can't ban another admin!", Color.Red);
@ -756,7 +774,9 @@ namespace TShockAPI
} }
string ip = args.Parameters[0]; 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); 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) private static void ClearBans(CommandArgs args)
{ {
if (args.Parameters.Count < 1 && ClearBansCode == -1) if (args.Parameters.Count < 1 && ClearBansCode == -1)
@ -986,12 +1007,12 @@ namespace TShockAPI
int penis56 = 12; int penis56 = 12;
int penis57 = Main.rand.Next(Main.maxTilesX - 50) + 100; int penis57 = Main.rand.Next(Main.maxTilesX - 50) + 100;
penis57 *= 0x10; penis57 *= 0x10;
int penis58 = Main.rand.Next((int)(Main.maxTilesY * 0.05)) * 0x10; int penis58 = Main.rand.Next((int) (Main.maxTilesY*0.05))*0x10;
Vector2 vector = new Vector2(penis57, penis58); Vector2 vector = new Vector2(penis57, penis58);
float speedX = Main.rand.Next(-100, 0x65); float speedX = Main.rand.Next(-100, 0x65);
float speedY = Main.rand.Next(200) + 100; float speedY = Main.rand.Next(200) + 100;
float penis61 = (float)Math.Sqrt(((speedX * speedX) + (speedY * speedY))); float penis61 = (float) Math.Sqrt(((speedX*speedX) + (speedY*speedY)));
penis61 = (penis56) / penis61; penis61 = (penis56)/penis61;
speedX *= penis61; speedX *= penis61;
speedY *= penis61; speedY *= penis61;
Projectile.NewProjectile(vector.X, vector.Y, speedX, speedY, 12, 0x3e8, 10f, Main.myPlayer); Projectile.NewProjectile(vector.X, vector.Y, speedX, speedY, 12, 0x3e8, 10f, Main.myPlayer);
@ -1103,7 +1124,7 @@ namespace TShockAPI
private static void WoF(CommandArgs args) private static void WoF(CommandArgs args)
{ {
if (Main.wof >= 0 || (args.Player.Y / 16f < (Main.maxTilesY - 205))) if (Main.wof >= 0 || (args.Player.Y/16f < (Main.maxTilesY - 205)))
{ {
args.Player.SendMessage("Can't spawn Wall of Flesh!", Color.Red); args.Player.SendMessage("Can't spawn Wall of Flesh!", Color.Red);
return; return;
@ -1187,7 +1208,7 @@ namespace TShockAPI
args.Player.SendMessage("Invalid syntax! Proper syntax: /hardcore [amount]", Color.Red); args.Player.SendMessage("Invalid syntax! Proper syntax: /hardcore [amount]", Color.Red);
return; return;
} }
amount = Math.Min(amount, Main.maxNPCs / 4); amount = Math.Min(amount, Main.maxNPCs/4);
NPC retinazer = TShock.Utils.GetNPCById(125); NPC retinazer = TShock.Utils.GetNPCById(125);
NPC spaz = TShock.Utils.GetNPCById(126); NPC spaz = TShock.Utils.GetNPCById(126);
NPC destroyer = TShock.Utils.GetNPCById(134); NPC destroyer = TShock.Utils.GetNPCById(134);
@ -1241,13 +1262,15 @@ namespace TShockAPI
else else
{ {
var npc = npcs[0]; 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); 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)); TShock.Utils.Broadcast(string.Format("{0} was spawned {1} time(s).", npc.name, amount));
} }
else if (npc.type == 113) 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 else
args.Player.SendMessage("Invalid mob type!", Color.Red); args.Player.SendMessage("Invalid mob type!", Color.Red);
} }
@ -1389,7 +1412,7 @@ namespace TShockAPI
if (args.Player.Teleport(plr.TileX, plr.TileY + 3)) if (args.Player.Teleport(plr.TileX, plr.TileY + 3))
{ {
args.Player.SendMessage(string.Format("Teleported to {0}", plr.Name)); args.Player.SendMessage(string.Format("Teleported to {0}", plr.Name));
if(!args.Player.Group.HasPermission(Permissions.tphide)) if (!args.Player.Group.HasPermission(Permissions.tphide))
plr.SendMessage(args.Player.Name + " Teleported To You"); plr.SendMessage(args.Player.Name + " Teleported To You");
} }
} }
@ -1478,7 +1501,7 @@ namespace TShockAPI
var plr = foundplr[0]; var plr = foundplr[0];
if (warp.WarpPos != Vector2.Zero) if (warp.WarpPos != Vector2.Zero)
{ {
if (plr.Teleport((int)warp.WarpPos.X, (int)warp.WarpPos.Y + 3)) if (plr.Teleport((int) warp.WarpPos.X, (int) warp.WarpPos.Y + 3))
{ {
plr.SendMessage(string.Format("{0} Warped you to {1}", args.Player.Name, warpName), Color.Yellow); plr.SendMessage(string.Format("{0} Warped you to {1}", args.Player.Name, warpName), Color.Yellow);
args.Player.SendMessage(string.Format("You warped {0} to {1}.", plr.Name, warpName), Color.Yellow); args.Player.SendMessage(string.Format("You warped {0} to {1}.", plr.Name, warpName), Color.Yellow);
@ -1582,7 +1605,7 @@ namespace TShockAPI
var warps = TShock.Warps.ListAllPublicWarps(Main.worldID.ToString()); var warps = TShock.Warps.ListAllPublicWarps(Main.worldID.ToString());
//Check if they are trying to access a page that doesn't exist. //Check if they are trying to access a page that doesn't exist.
int pagecount = warps.Count / pagelimit; int pagecount = warps.Count/pagelimit;
if (page > pagecount) if (page > pagecount)
{ {
args.Player.SendMessage(string.Format("Page number exceeds pages ({0}/{1})", page + 1, pagecount + 1), Color.Red); args.Player.SendMessage(string.Format("Page number exceeds pages ({0}/{1})", page + 1, pagecount + 1), Color.Red);
@ -1594,7 +1617,7 @@ namespace TShockAPI
//Add up to pagelimit names to a list //Add up to pagelimit names to a list
var nameslist = new List<string>(); var nameslist = new List<string>();
for (int i = (page * pagelimit); (i < ((page * pagelimit) + pagelimit)) && i < warps.Count; i++) for (int i = (page*pagelimit); (i < ((page*pagelimit) + pagelimit)) && i < warps.Count; i++)
{ {
nameslist.Add(warps[i].WarpName); nameslist.Add(warps[i].WarpName);
} }
@ -1617,7 +1640,7 @@ namespace TShockAPI
var warp = TShock.Warps.FindWarp(warpName); var warp = TShock.Warps.FindWarp(warpName);
if (warp.WarpPos != Vector2.Zero) if (warp.WarpPos != Vector2.Zero)
{ {
if (args.Player.Teleport((int)warp.WarpPos.X, (int)warp.WarpPos.Y + 3)) if (args.Player.Teleport((int) warp.WarpPos.X, (int) warp.WarpPos.Y + 3))
args.Player.SendMessage("Warped to " + warpName, Color.Yellow); args.Player.SendMessage("Warped to " + warpName, Color.Yellow);
} }
else else
@ -1782,7 +1805,8 @@ namespace TShockAPI
FileTools.SetupConfig(); FileTools.SetupConfig();
TShock.Groups.LoadPermisions(); TShock.Groups.LoadPermisions();
TShock.Regions.ReloadAllRegions(); 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) private static void ServerPassword(CommandArgs args)
@ -1806,7 +1830,6 @@ namespace TShockAPI
private static void Settle(CommandArgs args) private static void Settle(CommandArgs args)
{ {
if (Liquid.panicMode) if (Liquid.panicMode)
{ {
args.Player.SendMessage("Liquid is already settling!", Color.Red); args.Player.SendMessage("Liquid is already settling!", Color.Red);
@ -1814,7 +1837,6 @@ namespace TShockAPI
} }
Liquid.StartPanic(); Liquid.StartPanic();
TShock.Utils.Broadcast("Settling all liquids..."); TShock.Utils.Broadcast("Settling all liquids...");
} }
private static void MaxSpawns(CommandArgs args) private static void MaxSpawns(CommandArgs args)
@ -1949,7 +1971,8 @@ namespace TShockAPI
{ {
foreach (Region r in TShock.Regions.Regions) 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) foreach (int s in r.AllowedIDs)
{ {
args.Player.SendMessage(r.Name + ": " + s); 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 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); 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[0] = Point.Zero;
args.Player.TempPoints[1] = Point.Zero; args.Player.TempPoints[1] = Point.Zero;
@ -2240,7 +2264,7 @@ namespace TShockAPI
} }
//Check if they are trying to access a page that doesn't exist. //Check if they are trying to access a page that doesn't exist.
int pagecount = regions.Count / pagelimit; int pagecount = regions.Count/pagelimit;
if (page > pagecount) if (page > pagecount)
{ {
args.Player.SendMessage(string.Format("Page number exceeds pages ({0}/{1})", page + 1, pagecount + 1), Color.Red); args.Player.SendMessage(string.Format("Page number exceeds pages ({0}/{1})", page + 1, pagecount + 1), Color.Red);
@ -2252,7 +2276,7 @@ namespace TShockAPI
//Add up to pagelimit names to a list //Add up to pagelimit names to a list
var nameslist = new List<string>(); var nameslist = new List<string>();
for (int i = (page * pagelimit); (i < ((page * pagelimit) + pagelimit)) && i < regions.Count; i++) for (int i = (page*pagelimit); (i < ((page*pagelimit) + pagelimit)) && i < regions.Count; i++)
{ {
nameslist.Add(regions[i].Name); nameslist.Add(regions[i].Name);
} }
@ -2284,7 +2308,8 @@ namespace TShockAPI
break; 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) foreach (int s in r.AllowedIDs)
{ {
var user = TShock.Users.GetUserByID(s); var user = TShock.Users.GetUserByID(s);
@ -2345,12 +2370,14 @@ namespace TShockAPI
} }
else 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 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; break;
} }
@ -2358,7 +2385,8 @@ namespace TShockAPI
default: default:
{ {
args.Player.SendMessage("Avialable region commands:", Color.Green); 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 name (provides region name)", Color.Yellow);
args.Player.SendMessage("/region delete [name] /region clear (temporary region)", Color.Yellow); args.Player.SendMessage("/region delete [name] /region clear (temporary region)", Color.Yellow);
args.Player.SendMessage("/region allow [name] [regionname]", Color.Yellow); args.Player.SendMessage("/region allow [name] [regionname]", Color.Yellow);
@ -2387,9 +2415,9 @@ namespace TShockAPI
} }
} }
var sb = new StringBuilder(); var sb = new StringBuilder();
if (cmdlist.Count > (15 * (page - 1))) if (cmdlist.Count > (15*(page - 1)))
{ {
for (int j = (15 * (page - 1)); j < (15 * page); j++) for (int j = (15*(page - 1)); j < (15*page); j++)
{ {
if (sb.Length != 0) if (sb.Length != 0)
sb.Append(", "); sb.Append(", ");
@ -2399,14 +2427,14 @@ namespace TShockAPI
args.Player.SendMessage(sb.ToString(), Color.Yellow); args.Player.SendMessage(sb.ToString(), Color.Yellow);
break; break;
} }
if ((j + 1) % 5 == 0) if ((j + 1)%5 == 0)
{ {
args.Player.SendMessage(sb.ToString(), Color.Yellow); args.Player.SendMessage(sb.ToString(), Color.Yellow);
sb.Clear(); sb.Clear();
} }
} }
} }
if (cmdlist.Count > (15 * page)) if (cmdlist.Count > (15*page))
{ {
args.Player.SendMessage(string.Format("Type /help {0} for more commands.", (page + 1)), Color.Yellow); args.Player.SendMessage(string.Format("Type /help {0} for more commands.", (page + 1)), Color.Yellow);
} }
@ -2415,7 +2443,8 @@ namespace TShockAPI
private static void Playing(CommandArgs args) 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("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) private static void AuthToken(CommandArgs args)
@ -2555,7 +2584,6 @@ namespace TShockAPI
} }
else else
args.Player.SendMessage("You cannot mute this player."); args.Player.SendMessage("You cannot mute this player.");
} }
private static void Motd(CommandArgs args) private static void Motd(CommandArgs args)
@ -2609,7 +2637,8 @@ namespace TShockAPI
args.Player.SendMessage("(Whisper To)" + "<" + args.Player.LastWhisper.Name + ">" + msg, Color.MediumPurple); args.Player.SendMessage("(Whisper To)" + "<" + args.Player.LastWhisper.Name + ">" + msg, Color.MediumPurple);
} }
else 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) private static void Annoy(CommandArgs args)
@ -2694,7 +2723,8 @@ namespace TShockAPI
{ {
if (args.Parameters.Count < 1) 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; return;
} }
if (args.Parameters[0].Length == 0) if (args.Parameters[0].Length == 0)
@ -2750,7 +2780,8 @@ namespace TShockAPI
{ {
if (args.Parameters.Count < 2) 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; return;
} }
if (args.Parameters[0].Length == 0) if (args.Parameters[0].Length == 0)
@ -2827,13 +2858,12 @@ namespace TShockAPI
public static void ClearItems(CommandArgs args) public static void ClearItems(CommandArgs args)
{ {
int radius = 50; int radius = 50;
if (args.Parameters.Count > 0) if (args.Parameters.Count > 0)
{ {
if (args.Parameters[0].ToLower() == "all") if (args.Parameters[0].ToLower() == "all")
{ {
radius = Int32.MaxValue / 16; radius = Int32.MaxValue/16;
} }
else else
{ {
@ -2841,14 +2871,20 @@ namespace TShockAPI
{ {
radius = Convert.ToInt32(args.Parameters[0]); 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; int count = 0;
for (int i = 0; i < 200; i++) 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; Main.item[i].active = false;
NetMessage.SendData(0x15, -1, -1, "", i, 0f, 0f, 0f, 0); 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."); args.Player.SendMessage("All " + count + " items within a radius of " + radius + " have been deleted.");
} }
private static void Heal(CommandArgs args) private static void Heal(CommandArgs args)
@ -2938,9 +2973,10 @@ namespace TShockAPI
{ {
if (time < 0 || time > short.MaxValue) if (time < 0 || time > short.MaxValue)
time = 60; time = 60;
args.Player.SetBuff(id, time * 60); args.Player.SetBuff(id, time*60);
args.Player.SendMessage(string.Format("You have buffed yourself with {0}({1}) for {2} seconds!", 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 else
args.Player.SendMessage("Invalid buff ID!", Color.Red); args.Player.SendMessage("Invalid buff ID!", Color.Red);
@ -2989,11 +3025,13 @@ namespace TShockAPI
{ {
if (time < 0 || time > short.MaxValue) if (time < 0 || time > short.MaxValue)
time = 60; time = 60;
foundplr[0].SetBuff(id, time * 60); foundplr[0].SetBuff(id, time*60);
args.Player.SendMessage(string.Format("You have buffed {0} with {1}({2}) for {3} seconds!", 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!", 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 else
args.Player.SendMessage("Invalid buff ID!", Color.Red); args.Player.SendMessage("Invalid buff ID!", Color.Red);

View file

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

View file

@ -32,11 +32,14 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("Bans", var table = new SqlTable("Bans",
new SqlColumn("IP", MySqlDbType.String, 16) { Primary = true }, new SqlColumn("IP", MySqlDbType.String, 16) {Primary = true},
new SqlColumn("Name", MySqlDbType.Text), new SqlColumn("Name", MySqlDbType.Text),
new SqlColumn("Reason", 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); creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "bans.txt"); String file = Path.Combine(TShock.SavePath, "bans.txt");
@ -98,7 +101,6 @@ namespace TShockAPI.DB
{ {
if (reader.Read()) if (reader.Read())
return new Ban(reader.Get<string>("IP"), reader.Get<string>("Name"), reader.Get<string>("Reason")); return new Ban(reader.Get<string>("IP"), reader.Get<string>("Name"), reader.Get<string>("Reason"));
} }
} }
catch (Exception ex) catch (Exception ex)
@ -133,6 +135,7 @@ namespace TShockAPI.DB
} }
return false; return false;
} }
public bool ClearBans() public bool ClearBans()
{ {
try try

View file

@ -18,21 +18,25 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("GroupList", var table = new SqlTable("GroupList",
new SqlColumn("GroupName", MySqlDbType.VarChar, 32) { Primary = true }, new SqlColumn("GroupName", MySqlDbType.VarChar, 32) {Primary = true},
new SqlColumn("Parent", MySqlDbType.VarChar, 32), new SqlColumn("Parent", MySqlDbType.VarChar, 32),
new SqlColumn("Commands", MySqlDbType.Text), new SqlColumn("Commands", MySqlDbType.Text),
new SqlColumn("ChatColor", MySqlDbType.Text), new SqlColumn("ChatColor", MySqlDbType.Text),
new SqlColumn("Prefix", MySqlDbType.Text), new SqlColumn("Prefix", MySqlDbType.Text),
new SqlColumn("Suffix", 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); creator.EnsureExists(table);
//Add default groups //Add default groups
AddGroup("guest", "canbuild,canregister,canlogin,canpartychat,cantalkinthird"); AddGroup("guest", "canbuild,canregister,canlogin,canpartychat,cantalkinthird");
AddGroup("default", "guest", "warp,canchangepassword"); AddGroup("default", "guest", "warp,canchangepassword");
AddGroup("newadmin", "default", "kick,editspawn,reservedslot"); 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("trustedadmin", "admin", "maintenance,cfg,butcher,item,heal,immunetoban,usebanneditem,manageusers");
AddGroup("vip", "default", "reservedslot"); AddGroup("vip", "default", "reservedslot");
@ -63,7 +67,6 @@ namespace TShockAPI.DB
query = "INSERT IGNORE INTO GroupList SET GroupName=@0, Commands=@1;"; query = "INSERT IGNORE INTO GroupList SET GroupName=@0, Commands=@1;";
db.Query(query, info[0].Trim(), comms); db.Query(query, info[0].Trim(), comms);
} }
} }
} }
@ -75,7 +78,6 @@ namespace TShockAPI.DB
File.Delete(file2); File.Delete(file2);
File.Move(file, file2); File.Move(file, file2);
} }
} }
@ -114,9 +116,9 @@ namespace TShockAPI.DB
group.Parent = parent; group.Parent = parent;
} }
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ? string query = (TShock.Config.StorageType.ToLower() == "sqlite")
"INSERT OR IGNORE INTO GroupList (GroupName, Parent, Commands, ChatColor) VALUES (@0, @1, @2, @3);" : ? "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"; : "INSERT IGNORE INTO GroupList SET GroupName=@0, Parent=@1, Commands=@2, ChatColor=@3";
if (database.Query(query, name, parentname, permissions, chatcolor) == 1) if (database.Query(query, name, parentname, permissions, chatcolor) == 1)
message = "Group " + name + " has been created successfully."; message = "Group " + name + " has been created successfully.";
@ -124,10 +126,12 @@ namespace TShockAPI.DB
return message; return message;
} }
public String AddGroup(String name, String permissions) public String AddGroup(String name, String permissions)
{ {
return AddGroup(name, "", permissions, "255,255,255"); return AddGroup(name, "", permissions, "255,255,255");
} }
public String AddGroup(String name, string parent, String permissions) public String AddGroup(String name, string parent, String permissions)
{ {
return AddGroup(name, parent, permissions, "255,255,255"); return AddGroup(name, parent, permissions, "255,255,255");
@ -159,7 +163,7 @@ namespace TShockAPI.DB
if (database.Query("UPDATE GroupList SET Commands=@0 WHERE GroupName=@1", String.Join(",", permissions), name) != 0) if (database.Query("UPDATE GroupList SET Commands=@0 WHERE GroupName=@1", String.Join(",", permissions), name) != 0)
{ {
message = "Group " + name + " has been modified successfully."; message = "Group " + name + " has been modified successfully.";
group.SetPermission( permissions ); group.SetPermission(permissions);
} }
return message; return message;
} }
@ -173,12 +177,12 @@ namespace TShockAPI.DB
var group = TShock.Utils.GetGroup(name); var group = TShock.Utils.GetGroup(name);
//Only get permissions that exist in the group. //Only get permissions that exist in the group.
var newperms = group.permissions.Except( permissions ); var newperms = group.permissions.Except(permissions);
if (database.Query("UPDATE GroupList SET Commands=@0 WHERE GroupName=@1", String.Join(",", newperms), name) != 0) if (database.Query("UPDATE GroupList SET Commands=@0 WHERE GroupName=@1", String.Join(",", newperms), name) != 0)
{ {
message = "Group " + name + " has been modified successfully."; message = "Group " + name + " has been modified successfully.";
group.SetPermission( newperms.ToList() ); group.SetPermission(newperms.ToList());
} }
return message; return message;
} }
@ -203,7 +207,7 @@ namespace TShockAPI.DB
var group = new Group(groupname); var group = new Group(groupname);
group.Prefix = reader.Get<String>("Prefix"); group.Prefix = reader.Get<String>("Prefix");
group.Suffix= reader.Get<String>("Suffix"); group.Suffix = reader.Get<String>("Suffix");
//Inherit Given commands //Inherit Given commands
String[] commands = reader.Get<String>("Commands").Split(','); String[] commands = reader.Get<String>("Commands").Split(',');

View file

@ -22,10 +22,17 @@ namespace TShockAPI.DB
{ {
public string CreateTable(SqlTable table) 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)); return "CREATE TABLE '{0}' ({1})".SFormat(table.Name, string.Join(", ", columns));
} }
static Random rand = new Random();
private static Random rand = new Random();
/// <summary> /// <summary>
/// Alter a table from source to destination /// Alter a table from source to destination
/// </summary> /// </summary>
@ -39,7 +46,13 @@ namespace TShockAPI.DB
var create = CreateTable(to); var create = CreateTable(to);
//combine all columns in the 'from' variable excluding ones that aren't in the 'to' variable. //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? //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); var drop = "DROP TABLE '{0}_{1}'".SFormat(rstr, from.Name);
return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop); return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop);
/* /*
@ -51,6 +64,7 @@ namespace TShockAPI.DB
* Twitchy - Oh. I get it! * Twitchy - Oh. I get it!
*/ */
} }
public string DeleteRow(string table, List<SqlValue> wheres) public string DeleteRow(string table, List<SqlValue> wheres)
{ {
var sbwheres = new StringBuilder(); var sbwheres = new StringBuilder();
@ -67,6 +81,7 @@ namespace TShockAPI.DB
else else
return "DELETE FROM '{0}'".SFormat(table, sbwheres.ToString()); return "DELETE FROM '{0}'".SFormat(table, sbwheres.ToString());
} }
public string UpdateValue(string table, List<SqlValue> values, List<SqlValue> wheres) public string UpdateValue(string table, List<SqlValue> values, List<SqlValue> wheres)
{ {
var sbvalues = new StringBuilder(); var sbvalues = new StringBuilder();
@ -93,6 +108,7 @@ namespace TShockAPI.DB
else else
return "UPDATE '{0}' SET {1}".SFormat(table, sbvalues.ToString()); return "UPDATE '{0}' SET {1}".SFormat(table, sbvalues.ToString());
} }
public string InsertValues(string table, List<SqlValue> values) public string InsertValues(string table, List<SqlValue> values)
{ {
var sbnames = new StringBuilder(); var sbnames = new StringBuilder();
@ -117,6 +133,7 @@ namespace TShockAPI.DB
} }
return "INSERT INTO '{0}' ({1}) VALUES ({2})".SFormat(table, sbnames.ToString(), sbvalues.ToString()); return "INSERT INTO '{0}' ({1}) VALUES ({2})".SFormat(table, sbnames.ToString(), sbvalues.ToString());
} }
public string ReadColumn(string table, List<SqlValue> wheres) public string ReadColumn(string table, List<SqlValue> wheres)
{ {
var sbwheres = new StringBuilder(); var sbwheres = new StringBuilder();
@ -130,13 +147,13 @@ namespace TShockAPI.DB
count++; count++;
} }
if(wheres.Count > 0) if (wheres.Count > 0)
return "SELECT * FROM {0} WHERE {1}".SFormat(table, sbwheres.ToString()); return "SELECT * FROM {0} WHERE {1}".SFormat(table, sbwheres.ToString());
else else
return "SELECT * FROM {0}".SFormat(table); 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.VarChar, "TEXT"},
{MySqlDbType.String, "TEXT"}, {MySqlDbType.String, "TEXT"},
@ -146,23 +163,34 @@ namespace TShockAPI.DB
{MySqlDbType.LongText, "TEXT"}, {MySqlDbType.LongText, "TEXT"},
{MySqlDbType.Int32, "INTEGER"}, {MySqlDbType.Int32, "INTEGER"},
}; };
public string DbTypeToString(MySqlDbType type, int? length) public string DbTypeToString(MySqlDbType type, int? length)
{ {
string ret; string ret;
if (TypesAsStrings.TryGetValue(type, out ret)) if (TypesAsStrings.TryGetValue(type, out ret))
return ret; return ret;
throw new NotImplementedException(Enum.GetName(typeof(MySqlDbType), type)); throw new NotImplementedException(Enum.GetName(typeof (MySqlDbType), type));
} }
} }
public class MysqlQueryCreator : IQueryBuilder public class MysqlQueryCreator : IQueryBuilder
{ {
public string CreateTable(SqlTable table) 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); 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> /// <summary>
/// Alter a table from source to destination /// Alter a table from source to destination
/// </summary> /// </summary>
@ -176,10 +204,17 @@ namespace TShockAPI.DB
var create = CreateTable(to); var create = CreateTable(to);
//combine all columns in the 'from' variable excluding ones that aren't in the 'to' variable. //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? //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); var drop = "DROP TABLE {0}_{1}".SFormat(rstr, from.Name);
return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop); return "{0}; {1}; {2}; {3};".SFormat(alter, create, insert, drop);
} }
public string DeleteRow(string table, List<SqlValue> wheres) public string DeleteRow(string table, List<SqlValue> wheres)
{ {
var sbwheres = new StringBuilder(); var sbwheres = new StringBuilder();
@ -196,6 +231,7 @@ namespace TShockAPI.DB
else else
return "DELETE FROM {0}".SFormat(table, sbwheres.ToString()); return "DELETE FROM {0}".SFormat(table, sbwheres.ToString());
} }
public string UpdateValue(string table, List<SqlValue> values, List<SqlValue> wheres) public string UpdateValue(string table, List<SqlValue> values, List<SqlValue> wheres)
{ {
var sbvalues = new StringBuilder(); var sbvalues = new StringBuilder();
@ -222,6 +258,7 @@ namespace TShockAPI.DB
else else
return "UPDATE {0} SET {1}".SFormat(table, sbvalues.ToString()); return "UPDATE {0} SET {1}".SFormat(table, sbvalues.ToString());
} }
public string InsertValues(string table, List<SqlValue> values) public string InsertValues(string table, List<SqlValue> values)
{ {
var sbnames = new StringBuilder(); var sbnames = new StringBuilder();
@ -247,6 +284,7 @@ namespace TShockAPI.DB
return "INSERT INTO {0} ({1}) VALUES ({2})".SFormat(table, sbnames.ToString(), sbvalues.ToString()); return "INSERT INTO {0} ({1}) VALUES ({2})".SFormat(table, sbnames.ToString(), sbvalues.ToString());
} }
public string ReadColumn(string table, List<SqlValue> wheres) public string ReadColumn(string table, List<SqlValue> wheres)
{ {
var sbwheres = new StringBuilder(); var sbwheres = new StringBuilder();
@ -266,7 +304,7 @@ namespace TShockAPI.DB
return "SELECT * FROM {0}".SFormat(table); 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.VarChar, "VARCHAR"},
{MySqlDbType.String, "CHAR"}, {MySqlDbType.String, "CHAR"},
@ -276,12 +314,13 @@ namespace TShockAPI.DB
{MySqlDbType.LongText, "LONGTEXT"}, {MySqlDbType.LongText, "LONGTEXT"},
{MySqlDbType.Int32, "INT"}, {MySqlDbType.Int32, "INT"},
}; };
public string DbTypeToString(MySqlDbType type, int? length) public string DbTypeToString(MySqlDbType type, int? length)
{ {
string ret; string ret;
if (TypesAsStrings.TryGetValue(type, out ret)) if (TypesAsStrings.TryGetValue(type, out ret))
return ret + (length != null ? "({0})".SFormat((int)length) : ""); return ret + (length != null ? "({0})".SFormat((int) length) : "");
throw new NotImplementedException(Enum.GetName(typeof(MySqlDbType), type)); throw new NotImplementedException(Enum.GetName(typeof (MySqlDbType), type));
} }
} }
} }

View file

@ -31,12 +31,15 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("Inventory", var table = new SqlTable("Inventory",
new SqlColumn("Account", MySqlDbType.Int32) { Primary = true }, new SqlColumn("Account", MySqlDbType.Int32) {Primary = true},
new SqlColumn("MaxHealth", MySqlDbType.Int32), new SqlColumn("MaxHealth", MySqlDbType.Int32),
new SqlColumn("MaxMana", MySqlDbType.Int32), new SqlColumn("MaxMana", MySqlDbType.Int32),
new SqlColumn("Inventory", MySqlDbType.Text) 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); creator.EnsureExists(table);
} }
@ -76,7 +79,8 @@ namespace TShockAPI.DB
{ {
try 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; return true;
} }
catch (Exception ex) catch (Exception ex)
@ -88,7 +92,8 @@ namespace TShockAPI.DB
{ {
try 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; return true;
} }
catch (Exception ex) catch (Exception ex)

View file

@ -17,10 +17,13 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("ItemBans", var table = new SqlTable("ItemBans",
new SqlColumn("ItemName", MySqlDbType.VarChar, 50) { Primary = true }, new SqlColumn("ItemName", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("AllowedGroups", MySqlDbType.Text ) 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); creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "itembans.txt"); String file = Path.Combine(TShock.SavePath, "itembans.txt");
@ -33,10 +36,9 @@ namespace TShockAPI.DB
{ {
if (!line.Equals("") && !line.Substring(0, 1).Equals("#")) if (!line.Equals("") && !line.Substring(0, 1).Equals("#"))
{ {
string query = (TShock.Config.StorageType.ToLower() == "sqlite")
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ? ? "INSERT OR IGNORE INTO 'ItemBans' (ItemName, AllowedGroups) VALUES (@0, @1);"
"INSERT OR IGNORE INTO 'ItemBans' (ItemName, AllowedGroups) VALUES (@0, @1);" : : "INSERT IGNORE INTO ItemBans SET ItemName=@0,AllowedGroups=@1 ;";
"INSERT IGNORE INTO ItemBans SET ItemName=@0,AllowedGroups=@1 ;";
int id = 0; int id = 0;
int.TryParse(line, out id); int.TryParse(line, out id);
@ -67,7 +69,7 @@ namespace TShockAPI.DB
while (reader != null && reader.Read()) while (reader != null && reader.Read())
{ {
ItemBan ban = new ItemBan(reader.Get<string>("ItemName")); ItemBan ban = new ItemBan(reader.Get<string>("ItemName"));
ban.SetAllowedGroups( reader.Get<string>("AllowedGroups") ); ban.SetAllowedGroups(reader.Get<string>("AllowedGroups"));
ItemBans.Add(ban); ItemBans.Add(ban);
} }
} }
@ -77,9 +79,10 @@ namespace TShockAPI.DB
{ {
try 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)) if (!ItemIsBanned(itemname, null))
ItemBans.Add( new ItemBan(itemname) ); ItemBans.Add(new ItemBan(itemname));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -94,7 +97,7 @@ namespace TShockAPI.DB
try try
{ {
database.Query("Delete FROM 'ItemBans' WHERE ItemName=@0;", TShock.Utils.GetItemByName(itemname)[0].name); database.Query("Delete FROM 'ItemBans' WHERE ItemName=@0;", TShock.Utils.GetItemByName(itemname)[0].name);
ItemBans.Remove( new ItemBan(itemname) ); ItemBans.Remove(new ItemBan(itemname));
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -113,7 +116,7 @@ namespace TShockAPI.DB
public bool ItemIsBanned(string name, TSPlayer ply) public bool ItemIsBanned(string name, TSPlayer ply)
{ {
if (ItemBans.Contains( new ItemBan(name) ) ) if (ItemBans.Contains(new ItemBan(name)))
{ {
ItemBan b = GetItemBanByName(name); ItemBan b = GetItemBanByName(name);
return !b.HasPermissionToUseItem(ply); return !b.HasPermissionToUseItem(ply);
@ -197,10 +200,11 @@ namespace TShockAPI.DB
{ {
if (ply == null) if (ply == null)
return false; 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 ) public void SetAllowedGroups(String groups)
{ {
// prevent null pointer exceptions // prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups)) if (!string.IsNullOrEmpty(groups))
@ -221,5 +225,4 @@ namespace TShockAPI.DB
return AllowedGroups.Remove(groupName); return AllowedGroups.Remove(groupName);
} }
} }
} }

View file

@ -42,20 +42,21 @@ namespace TShockAPI.DB
new SqlColumn("Y1", MySqlDbType.Int32), new SqlColumn("Y1", MySqlDbType.Int32),
new SqlColumn("width", MySqlDbType.Int32), new SqlColumn("width", MySqlDbType.Int32),
new SqlColumn("height", MySqlDbType.Int32), new SqlColumn("height", MySqlDbType.Int32),
new SqlColumn("RegionName", MySqlDbType.VarChar, 50) { Primary = true }, new SqlColumn("RegionName", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("WorldID", MySqlDbType.Text), new SqlColumn("WorldID", MySqlDbType.Text),
new SqlColumn("UserIds", MySqlDbType.Text), new SqlColumn("UserIds", MySqlDbType.Text),
new SqlColumn("Protected", MySqlDbType.Int32), new SqlColumn("Protected", MySqlDbType.Int32),
new SqlColumn("Groups", MySqlDbType.Text), new SqlColumn("Groups", MySqlDbType.Text),
new SqlColumn("Owner", MySqlDbType.VarChar, 50) 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); creator.EnsureExists(table);
ImportOld(); ImportOld();
ReloadAllRegions(); ReloadAllRegions();
} }
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
@ -68,7 +69,7 @@ namespace TShockAPI.DB
Region region; Region region;
Rectangle rect; Rectangle rect;
using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings { CloseInput = true })) using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings {CloseInput = true}))
{ {
// Parse the file and display each of the nodes. // Parse the file and display each of the nodes.
while (reader.Read()) while (reader.Read())
@ -130,14 +131,14 @@ namespace TShockAPI.DB
} }
region.Area = rect; region.Area = rect;
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ? string query = (TShock.Config.StorageType.ToLower() == "sqlite")
"INSERT OR IGNORE INTO Regions VALUES (@0, @1, @2, @3, @4, @5, @6, @7);" : ? "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;"; : "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); 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 //Todo: What should this be? We don't really have a way to go from ips to userids
/*string.Join(",", region.AllowedIDs)*/ /*string.Join(",", region.AllowedIDs)*/
} }
} }
@ -184,10 +185,10 @@ namespace TShockAPI.DB
string owner = reader.Get<string>("Owner"); string owner = reader.Get<string>("Owner");
string groups = reader.Get<string>("Groups"); string groups = reader.Get<string>("Groups");
string[] splitids = mergedids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); string[] splitids = mergedids.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries);
Region r = new Region(new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString()); Region r = new Region(new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString());
r.SetAllowedGroups( groups ); r.SetAllowedGroups(groups);
try try
{ {
for (int i = 0; i < splitids.Length; i++) for (int i = 0; i < splitids.Length; i++)
@ -220,7 +221,6 @@ namespace TShockAPI.DB
public void ReloadForUnitTest(String n) public void ReloadForUnitTest(String n)
{ {
using (var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", n)) using (var reader = database.QueryReader("SELECT * FROM Regions WHERE WorldID=@0", n))
{ {
Regions.Clear(); Regions.Clear();
@ -238,7 +238,7 @@ namespace TShockAPI.DB
string groups = reader.Get<string>("Groups"); string groups = reader.Get<string>("Groups");
Region r = new Region(new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString()); Region r = new Region(new Rectangle(X1, Y1, width, height), name, owner, Protected != 0, Main.worldID.ToString());
r.SetAllowedGroups( groups ); r.SetAllowedGroups(groups);
try try
{ {
for (int i = 0; i < SplitIDs.Length; i++) for (int i = 0; i < SplitIDs.Length; i++)
@ -263,7 +263,6 @@ namespace TShockAPI.DB
Regions.Add(r); Regions.Add(r);
} }
} }
} }
public bool AddRegion(int tx, int ty, int width, int height, string regionname, string owner, string worldid) 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 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); tx, ty, width, height, regionname, worldid, "", 1, "", owner);
Regions.Add(new Region(new Rectangle(tx, ty, width, height), regionname, owner, true, worldid)); Regions.Add(new Region(new Rectangle(tx, ty, width, height), regionname, owner, true, worldid));
return true; return true;
@ -306,7 +306,8 @@ namespace TShockAPI.DB
{ {
try 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); var region = GetRegionByName(name);
if (region != null) if (region != null)
region.DisableBuild = state; region.DisableBuild = state;
@ -382,7 +383,7 @@ namespace TShockAPI.DB
public static List<string> ListIDs(string MergedIDs) public static List<string> ListIDs(string MergedIDs)
{ {
return MergedIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList(); return MergedIDs.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).ToList();
} }
public bool resizeRegion(string regionName, int addAmount, int direction) public bool resizeRegion(string regionName, int addAmount, int direction)
@ -397,7 +398,9 @@ namespace TShockAPI.DB
int width = 0; int width = 0;
try 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()) if (reader.Read())
X = reader.Get<int>("X1"); X = reader.Get<int>("X1");
@ -436,7 +439,10 @@ namespace TShockAPI.DB
Y -= addAmount; Y -= addAmount;
height += 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) if (q > 0)
return true; return true;
} }
@ -461,12 +467,15 @@ namespace TShockAPI.DB
} }
return false; return false;
} }
public bool AddNewUser(string regionName, String userName) public bool AddNewUser(string regionName, String userName)
{ {
try try
{ {
string MergedIDs = string.Empty; 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()) if (reader.Read())
MergedIDs = reader.Get<string>("UserIds"); MergedIDs = reader.Get<string>("UserIds");
@ -506,7 +515,7 @@ namespace TShockAPI.DB
using (var reader = database.QueryReader("SELECT RegionName FROM Regions WHERE WorldID=@0", worldid)) using (var reader = database.QueryReader("SELECT RegionName FROM Regions WHERE WorldID=@0", worldid))
{ {
while (reader.Read()) while (reader.Read())
regions.Add(new Region { Name = reader.Get<string>("RegionName") }); regions.Add(new Region {Name = reader.Get<string>("RegionName")});
} }
} }
catch (Exception ex) catch (Exception ex)
@ -531,10 +540,10 @@ namespace TShockAPI.DB
return null; return null;
} }
public bool ChangeOwner( string regionName, string newOwner ) public bool ChangeOwner(string regionName, string newOwner)
{ {
var region = GetRegionByName(regionName); var region = GetRegionByName(regionName);
if( region != null ) if (region != null)
{ {
region.Owner = newOwner; region.Owner = newOwner;
int q = database.Query("UPDATE Regions SET Owner=@0 WHERE RegionName=@1 AND WorldID=@2", newOwner, int q = database.Query("UPDATE Regions SET Owner=@0 WHERE RegionName=@1 AND WorldID=@2", newOwner,
@ -545,10 +554,12 @@ namespace TShockAPI.DB
return false; return false;
} }
public bool AllowGroup( string regionName, string groups) public bool AllowGroup(string regionName, string groups)
{ {
string groupsNew = ""; 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()) if (reader.Read())
groupsNew = reader.Get<string>("Groups"); groupsNew = reader.Get<string>("Groups");
@ -561,9 +572,9 @@ namespace TShockAPI.DB
regionName, Main.worldID.ToString()); regionName, Main.worldID.ToString());
Region r = GetRegionByName(regionName); Region r = GetRegionByName(regionName);
if( r != null ) if (r != null)
{ {
r.SetAllowedGroups( groupsNew ); r.SetAllowedGroups(groupsNew);
} }
else else
{ {
@ -573,7 +584,7 @@ namespace TShockAPI.DB
return q > 0; return q > 0;
} }
public bool RemoveGroup( string regionName, string group ) public bool RemoveGroup(string regionName, string group)
{ {
Region r = GetRegionByName(regionName); Region r = GetRegionByName(regionName);
if (r != null) if (r != null)
@ -607,7 +618,6 @@ namespace TShockAPI.DB
Owner = owner; Owner = owner;
DisableBuild = disablebuild; DisableBuild = disablebuild;
WorldID = RegionWorldIDz; WorldID = RegionWorldIDz;
} }
public Region() public Region()
@ -645,7 +655,8 @@ namespace TShockAPI.DB
return true; 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) public void setAllowedIDs(String ids)
@ -662,7 +673,7 @@ namespace TShockAPI.DB
AllowedIDs = id_list; AllowedIDs = id_list;
} }
public void SetAllowedGroups( String groups ) public void SetAllowedGroups(String groups)
{ {
// prevent null pointer exceptions // prevent null pointer exceptions
if (!string.IsNullOrEmpty(groups)) if (!string.IsNullOrEmpty(groups))

View file

@ -32,13 +32,16 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("RememberedPos", var table = new SqlTable("RememberedPos",
new SqlColumn("Name", MySqlDbType.VarChar, 50) { Primary = true }, new SqlColumn("Name", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("IP", MySqlDbType.Text), new SqlColumn("IP", MySqlDbType.Text),
new SqlColumn("X", MySqlDbType.Int32), new SqlColumn("X", MySqlDbType.Int32),
new SqlColumn("Y", MySqlDbType.Int32), new SqlColumn("Y", MySqlDbType.Int32),
new SqlColumn("WorldID", MySqlDbType.Text) 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); creator.EnsureExists(table);
} }
@ -68,7 +71,8 @@ namespace TShockAPI.DB
{ {
try 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) catch (Exception ex)
{ {
@ -79,7 +83,8 @@ namespace TShockAPI.DB
{ {
try 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) catch (Exception ex)
{ {

View file

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

View file

@ -10,10 +10,12 @@ namespace TShockAPI.DB
{ {
public List<SqlColumn> Columns { get; protected set; } public List<SqlColumn> Columns { get; protected set; }
public string Name { get; protected set; } public string Name { get; protected set; }
public SqlTable(string name, params SqlColumn[] columns) public SqlTable(string name, params SqlColumn[] columns)
: this(name, new List<SqlColumn>(columns)) : this(name, new List<SqlColumn>(columns))
{ {
} }
public SqlTable(string name, List<SqlColumn> columns) public SqlTable(string name, List<SqlColumn> columns)
{ {
Name = name; Name = name;
@ -23,8 +25,9 @@ namespace TShockAPI.DB
public class SqlTableCreator public class SqlTableCreator
{ {
IDbConnection database; private IDbConnection database;
IQueryBuilder creator; private IQueryBuilder creator;
public SqlTableCreator(IDbConnection db, IQueryBuilder provider) public SqlTableCreator(IDbConnection db, IQueryBuilder provider)
{ {
database = db; database = db;
@ -62,7 +65,11 @@ namespace TShockAPI.DB
} }
else if (name == SqlType.Mysql) 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()) while (reader.Read())
ret.Add(reader.Get<string>("COLUMN_NAME")); ret.Add(reader.Get<string>("COLUMN_NAME"));

View file

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

View file

@ -1,5 +1,4 @@
 /*
/*
TShock, a server mod for Terraria TShock, a server mod for Terraria
Copyright (C) 2011 The TShock Team Copyright (C) 2011 The TShock Team
@ -33,13 +32,16 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("Users", var table = new SqlTable("Users",
new SqlColumn("ID", MySqlDbType.Int32) { Primary = true, AutoIncrement = true }, new SqlColumn("ID", MySqlDbType.Int32) {Primary = true, AutoIncrement = true},
new SqlColumn("Username", MySqlDbType.VarChar, 32) { Unique = true }, new SqlColumn("Username", MySqlDbType.VarChar, 32) {Unique = true},
new SqlColumn("Password", MySqlDbType.VarChar, 128), new SqlColumn("Password", MySqlDbType.VarChar, 128),
new SqlColumn("Usergroup", MySqlDbType.Text), new SqlColumn("Usergroup", MySqlDbType.Text),
new SqlColumn("IP", MySqlDbType.VarChar, 16) 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); creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "users.txt"); String file = Path.Combine(TShock.SavePath, "users.txt");
@ -73,9 +75,9 @@ namespace TShockAPI.DB
group = info[1]; group = info[1];
} }
string query = (TShock.Config.StorageType.ToLower() == "sqlite") ? string query = (TShock.Config.StorageType.ToLower() == "sqlite")
"INSERT OR IGNORE INTO Users (Username, Password, Usergroup, IP) VALUES (@0, @1, @2, @3)" : ? "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"; : "INSERT IGNORE INTO Users SET Username=@0, Password=@1, Usergroup=@2, IP=@3";
database.Query(query, username.Trim(), sha.Trim(), group.Trim(), ip.Trim()); database.Query(query, username.Trim(), sha.Trim(), group.Trim(), ip.Trim());
} }
@ -88,7 +90,6 @@ namespace TShockAPI.DB
File.Delete(file2); File.Delete(file2);
File.Move(file, file2); File.Move(file, file2);
} }
} }
/// <summary> /// <summary>
@ -102,7 +103,9 @@ namespace TShockAPI.DB
if (!TShock.Groups.GroupExists(user.Group)) if (!TShock.Groups.GroupExists(user.Group))
throw new GroupNotExistsException(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); throw new UserExistsException(user.Name);
} }
catch (Exception ex) catch (Exception ex)
@ -148,7 +151,9 @@ namespace TShockAPI.DB
{ {
try 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); throw new UserNotExistException(user.Name);
} }
catch (Exception ex) catch (Exception ex)
@ -248,35 +253,38 @@ namespace TShockAPI.DB
{ {
try try
{ {
return GetUser(new User { Name = name }); return GetUser(new User {Name = name});
} }
catch (UserManagerException) catch (UserManagerException)
{ {
return null; return null;
} }
} }
public User GetUserByID(int id) public User GetUserByID(int id)
{ {
try try
{ {
return GetUser(new User { ID = id }); return GetUser(new User {ID = id});
} }
catch (UserManagerException) catch (UserManagerException)
{ {
return null; return null;
} }
} }
public User GetUserByIP(string ip) public User GetUserByIP(string ip)
{ {
try try
{ {
return GetUser(new User { Address = ip }); return GetUser(new User {Address = ip});
} }
catch (UserManagerException) catch (UserManagerException)
{ {
return null; return null;
} }
} }
public User GetUser(User user) public User GetUser(User user)
{ {
try try
@ -327,6 +335,7 @@ namespace TShockAPI.DB
Password = pass; Password = pass;
Group = group; Group = group;
} }
public User() public User()
{ {
Address = ""; Address = "";
@ -342,14 +351,14 @@ namespace TShockAPI.DB
public UserManagerException(string message) public UserManagerException(string message)
: base(message) : base(message)
{ {
} }
public UserManagerException(string message, Exception inner) public UserManagerException(string message, Exception inner)
: base(message, inner) : base(message, inner)
{ {
}
}
}
}
[Serializable] [Serializable]
public class UserExistsException : UserManagerException public class UserExistsException : UserManagerException
{ {
@ -358,6 +367,7 @@ namespace TShockAPI.DB
{ {
} }
} }
[Serializable] [Serializable]
public class UserNotExistException : UserManagerException public class UserNotExistException : UserManagerException
{ {
@ -366,6 +376,7 @@ namespace TShockAPI.DB
{ {
} }
} }
[Serializable] [Serializable]
public class GroupNotExistsException : UserManagerException public class GroupNotExistsException : UserManagerException
{ {

View file

@ -37,13 +37,16 @@ namespace TShockAPI.DB
database = db; database = db;
var table = new SqlTable("Warps", var table = new SqlTable("Warps",
new SqlColumn("WarpName", MySqlDbType.VarChar, 50) { Primary = true }, new SqlColumn("WarpName", MySqlDbType.VarChar, 50) {Primary = true},
new SqlColumn("X", MySqlDbType.Int32), new SqlColumn("X", MySqlDbType.Int32),
new SqlColumn("Y", MySqlDbType.Int32), new SqlColumn("Y", MySqlDbType.Int32),
new SqlColumn("WorldID", MySqlDbType.Text), new SqlColumn("WorldID", MySqlDbType.Text),
new SqlColumn("Private", 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); creator.EnsureExists(table);
String file = Path.Combine(TShock.SavePath, "warps.xml"); String file = Path.Combine(TShock.SavePath, "warps.xml");
@ -54,7 +57,7 @@ namespace TShockAPI.DB
if (!File.Exists(file)) if (!File.Exists(file))
return; return;
using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings { CloseInput = true })) using (var reader = XmlReader.Create(new StreamReader(file), new XmlReaderSettings {CloseInput = true}))
{ {
// Parse the file and display each of the nodes. // Parse the file and display each of the nodes.
while (reader.Read()) while (reader.Read())
@ -111,7 +114,6 @@ namespace TShockAPI.DB
break; break;
} }
} }
} }
String path = Path.Combine(TShock.SavePath, "old_configs"); String path = Path.Combine(TShock.SavePath, "old_configs");
@ -167,17 +169,21 @@ namespace TShockAPI.DB
{ {
try 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()) if (reader.Read())
{ {
try 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 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");
} }
} }
} }
@ -206,11 +212,11 @@ namespace TShockAPI.DB
try try
{ {
if (reader.Get<String>("Private") == "0" || reader.Get<String>("Private") == null) if (reader.Get<String>("Private") == "0" || reader.Get<String>("Private") == null)
warps.Add(new Warp { WarpName = reader.Get<string>("WarpName") }); warps.Add(new Warp {WarpName = reader.Get<string>("WarpName")});
} }
catch catch
{ {
warps.Add(new Warp { WarpName = reader.Get<string>("WarpName") }); warps.Add(new Warp {WarpName = reader.Get<string>("WarpName")});
} }
} }
} }

View file

@ -7,7 +7,6 @@ namespace TShockAPI.DB
{ {
public static class DbExt public static class DbExt
{ {
/// <summary> /// <summary>
/// Executes a query on a database. /// Executes a query on a database.
/// </summary> /// </summary>
@ -31,6 +30,7 @@ namespace TShockAPI.DB
} }
} }
} }
/// <summary> /// <summary>
/// Executes a query on a database. /// Executes a query on a database.
/// </summary> /// </summary>
@ -60,7 +60,7 @@ namespace TShockAPI.DB
using (var com = db.CreateCommand()) using (var com = db.CreateCommand())
{ {
com.CommandText = query; com.CommandText = query;
foreach(var kv in values) foreach (var kv in values)
com.AddParameter("@" + kv.Key, kv.Value); com.AddParameter("@" + kv.Key, kv.Value);
return new QueryResult(db, com.ExecuteReader()); return new QueryResult(db, com.ExecuteReader());
@ -78,7 +78,7 @@ namespace TShockAPI.DB
public static IDbConnection CloneEx(this IDbConnection conn) public static IDbConnection CloneEx(this IDbConnection conn)
{ {
var clone = (IDbConnection)Activator.CreateInstance(conn.GetType()); var clone = (IDbConnection) Activator.CreateInstance(conn.GetType());
clone.ConnectionString = conn.ConnectionString; clone.ConnectionString = conn.ConnectionString;
return clone; return clone;
} }
@ -93,18 +93,49 @@ namespace TShockAPI.DB
return SqlType.Unknown; 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 (bool),
{typeof(Int16), (s, i) => s.GetInt16(i)}, (s, i) => s.GetBoolean(i)
{typeof(Int32), (s, i) => s.GetInt32(i)}, },
{typeof(Int64), (s, i) => s.GetInt64(i)}, {
{typeof(string), (s, i) => s.GetString(i)}, typeof (byte),
{typeof(decimal), (s, i) => s.GetDecimal(i)}, (s, i) => s.GetByte(i)
{typeof(float), (s, i) => s.GetFloat(i)}, },
{typeof(double), (s, i) => s.GetDouble(i)}, {
{typeof(object), (s, i) => s.GetValue(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) public static T Get<T>(this IDataReader reader, string column)
@ -117,8 +148,8 @@ namespace TShockAPI.DB
if (reader.IsDBNull(column)) if (reader.IsDBNull(column))
return default(T); return default(T);
if (ReadFuncs.ContainsKey(typeof(T))) if (ReadFuncs.ContainsKey(typeof (T)))
return (T)ReadFuncs[typeof(T)](reader, column); return (T) ReadFuncs[typeof (T)](reader, column);
throw new NotImplementedException(); throw new NotImplementedException();
} }
@ -176,6 +207,7 @@ namespace TShockAPI.DB
return false; return false;
return Reader.Read(); return Reader.Read();
} }
public T Get<T>(string column) public T Get<T>(string column)
{ {
if (Reader == null) if (Reader == null)
@ -183,5 +215,4 @@ namespace TShockAPI.DB
return Reader.Get<T>(Reader.GetOrdinal(column)); return Reader.Get<T>(Reader.GetOrdinal(column));
} }
} }
} }

View file

@ -13,13 +13,13 @@ namespace TShockAPI.Extensions
switch (rand.Next(0, 3)) switch (rand.Next(0, 3))
{ {
case 0: case 0:
sb.Append((char)rand.Next('a', 'z' + 1)); sb.Append((char) rand.Next('a', 'z' + 1));
break; break;
case 1: case 1:
sb.Append((char)rand.Next('A', 'Z' + 1)); sb.Append((char) rand.Next('A', 'Z' + 1));
break; break;
case 2: case 2:
sb.Append((char)rand.Next('0', '9' + 1)); sb.Append((char) rand.Next('0', '9' + 1));
break; break;
} }
} }

View file

@ -22,11 +22,30 @@ namespace TShockAPI
{ {
public class FileTools public class FileTools
{ {
internal static string RulesPath { get { return Path.Combine(TShock.SavePath, "rules.txt"); } } internal static string RulesPath
internal static string MotdPath { get { return Path.Combine(TShock.SavePath, "motd.txt"); } } {
internal static string WhitelistPath { get { return Path.Combine(TShock.SavePath, "whitelist.txt"); } } get { return Path.Combine(TShock.SavePath, "rules.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 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) public static void CreateFile(string file)
{ {
@ -52,7 +71,8 @@ namespace TShockAPI
} }
CreateIfNot(RulesPath, "Respect the admins!\nDon't use TNT!"); 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); CreateIfNot(WhitelistPath);
try try
@ -72,8 +92,6 @@ namespace TShockAPI
Log.Error("Config Exception"); Log.Error("Config Exception");
Log.Error(ex.ToString()); Log.Error(ex.ToString());
} }
} }
/// <summary> /// <summary>

View file

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

View file

@ -27,6 +27,7 @@ using TShockAPI.Net;
namespace TShockAPI namespace TShockAPI
{ {
public delegate bool GetDataHandlerDelegate(GetDataHandlerArgs args); public delegate bool GetDataHandlerDelegate(GetDataHandlerArgs args);
public class GetDataHandlerArgs : EventArgs public class GetDataHandlerArgs : EventArgs
{ {
public TSPlayer Player { get; private set; } public TSPlayer Player { get; private set; }
@ -43,6 +44,7 @@ namespace TShockAPI
Data = data; Data = data;
} }
} }
public static class GetDataHandlers public static class GetDataHandlers
{ {
private static Dictionary<PacketTypes, GetDataHandlerDelegate> GetDataHandlerDelegates; private static Dictionary<PacketTypes, GetDataHandlerDelegate> GetDataHandlerDelegates;
@ -193,7 +195,7 @@ namespace TShockAPI
var male = args.Data.ReadInt8(); var male = args.Data.ReadInt8();
args.Data.Position += 21; args.Data.Position += 21;
var difficulty = args.Data.ReadInt8(); var difficulty = args.Data.ReadInt8();
string name = Encoding.ASCII.GetString(args.Data.ReadBytes((int)(args.Data.Length - args.Data.Position - 1))); string name = Encoding.ASCII.GetString(args.Data.ReadBytes((int) (args.Data.Length - args.Data.Position - 1)));
if (!TShock.Utils.ValidString(name)) if (!TShock.Utils.ValidString(name))
{ {
@ -243,19 +245,19 @@ namespace TShockAPI
if (user != null && !TShock.Config.DisableLoginBeforeJoin) if (user != null && !TShock.Config.DisableLoginBeforeJoin)
{ {
args.Player.RequiresPassword = true; args.Player.RequiresPassword = true;
NetMessage.SendData((int)PacketTypes.PasswordRequired, args.Player.Index); NetMessage.SendData((int) PacketTypes.PasswordRequired, args.Player.Index);
return true; return true;
} }
else if (!string.IsNullOrEmpty(TShock.Config.ServerPassword)) else if (!string.IsNullOrEmpty(TShock.Config.ServerPassword))
{ {
args.Player.RequiresPassword = true; args.Player.RequiresPassword = true;
NetMessage.SendData((int)PacketTypes.PasswordRequired, args.Player.Index); NetMessage.SendData((int) PacketTypes.PasswordRequired, args.Player.Index);
return true; return true;
} }
if (args.Player.State == 1) if (args.Player.State == 1)
args.Player.State = 2; args.Player.State = 2;
NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index); NetMessage.SendData((int) PacketTypes.WorldInfo, args.Player.Index);
return true; return true;
} }
@ -264,7 +266,7 @@ namespace TShockAPI
if (!args.Player.RequiresPassword) if (!args.Player.RequiresPassword)
return true; return true;
string password = Encoding.ASCII.GetString(args.Data.ReadBytes((int)(args.Data.Length - args.Data.Position - 1))); string password = Encoding.ASCII.GetString(args.Data.ReadBytes((int) (args.Data.Length - args.Data.Position - 1)));
var user = TShock.Users.GetUserByName(args.Player.Name); var user = TShock.Users.GetUserByName(args.Player.Name);
if (user != null) if (user != null)
{ {
@ -276,7 +278,7 @@ namespace TShockAPI
if (args.Player.State == 1) if (args.Player.State == 1)
args.Player.State = 2; args.Player.State = 2;
NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index); NetMessage.SendData((int) PacketTypes.WorldInfo, args.Player.Index);
if (TShock.Config.ServerSideInventory) if (TShock.Config.ServerSideInventory)
{ {
@ -316,12 +318,12 @@ namespace TShockAPI
} }
if (!string.IsNullOrEmpty(TShock.Config.ServerPassword)) if (!string.IsNullOrEmpty(TShock.Config.ServerPassword))
{ {
if(TShock.Config.ServerPassword == password) if (TShock.Config.ServerPassword == password)
{ {
args.Player.RequiresPassword = false; args.Player.RequiresPassword = false;
if (args.Player.State == 1) if (args.Player.State == 1)
args.Player.State = 2; args.Player.State = 2;
NetMessage.SendData((int)PacketTypes.WorldInfo, args.Player.Index); NetMessage.SendData((int) PacketTypes.WorldInfo, args.Player.Index);
return true; return true;
} }
TShock.Utils.ForceKick(args.Player, "Incorrect Server Password"); TShock.Utils.ForceKick(args.Player, "Incorrect Server Password");
@ -348,22 +350,26 @@ namespace TShockAPI
TShock.HackedInventory(args.Player); 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); TShock.Utils.ForceKick(args.Player, TShock.Config.ServerFullReason);
return true; return true;
} }
NetMessage.SendData((int)PacketTypes.TimeSet, -1, -1, "", 0, 0, Main.sunModY, Main.moonModY); NetMessage.SendData((int) PacketTypes.TimeSet, -1, -1, "", 0, 0, Main.sunModY, Main.moonModY);
if (TShock.Config.EnableGeoIP && TShock.Geo != null) 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); TShock.Utils.Broadcast(args.Player.Name + " has joined from the " + args.Player.Country, Color.Yellow);
} }
else 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); TShock.Utils.Broadcast(args.Player.Name + " has joined", Color.Yellow);
} }
@ -397,7 +403,7 @@ namespace TShockAPI
return true; return true;
} }
var tiles = new NetTile[size, size]; var tiles = new NetTile[size,size];
for (int x = 0; x < size; x++) for (int x = 0; x < size; x++)
{ {
@ -422,11 +428,11 @@ namespace TShockAPI
var tile = Main.tile[realx, realy]; var tile = Main.tile[realx, realy];
var newtile = tiles[x, y]; var newtile = tiles[x, y];
if(TShock.CheckTilePermission(args.Player, x, y)) if (TShock.CheckTilePermission(args.Player, x, y))
{ {
continue; continue;
} }
if(TShock.CheckRangePermission(args.Player, x, y)) if (TShock.CheckRangePermission(args.Player, x, y))
{ {
continue; continue;
} }
@ -603,7 +609,8 @@ namespace TShockAPI
args.Player.SendTileSquare(tileX, tileY); args.Player.SendTileSquare(tileX, tileY);
return true; 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.Disable();
args.Player.SendTileSquare(tileX, tileY); args.Player.SendTileSquare(tileX, tileY);
@ -615,7 +622,8 @@ namespace TShockAPI
args.Player.SendTileSquare(tileX, tileY); args.Player.SendTileSquare(tileX, tileY);
return true; 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.Disable();
args.Player.SendTileSquare(tileX, tileY); args.Player.SendTileSquare(tileX, tileY);
@ -674,7 +682,8 @@ namespace TShockAPI
args.Player.TilesCreated.Add(coords, Main.tile[tileX, tileY].Data); 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++; args.Player.TileKillThreshold++;
var coords = new Vector2(tileX, tileY); var coords = new Vector2(tileX, tileY);
@ -702,10 +711,11 @@ namespace TShockAPI
if (args.TPlayer.hostile != pvp) if (args.TPlayer.hostile != pvp)
{ {
long seconds = (long)(DateTime.UtcNow - args.Player.LastPvpChange).TotalSeconds; long seconds = (long) (DateTime.UtcNow - args.Player.LastPvpChange).TotalSeconds;
if (seconds > 5) 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; args.Player.LastPvpChange = DateTime.UtcNow;
} }
@ -718,7 +728,7 @@ namespace TShockAPI
args.Player.Spawn(); args.Player.Spawn();
} }
NetMessage.SendData((int)PacketTypes.TogglePvp, -1, -1, "", args.Player.Index); NetMessage.SendData((int) PacketTypes.TogglePvp, -1, -1, "", args.Player.Index);
return true; return true;
} }
@ -736,14 +746,15 @@ namespace TShockAPI
return true; return true;
} }
if(args.Player.LastNetPosition == Vector2.Zero) if (args.Player.LastNetPosition == Vector2.Zero)
{ {
return true; return true;
} }
if (!pos.Equals(args.Player.LastNetPosition)) 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 (TShock.CheckIgnores(args.Player))
{ {
if (distance > TShock.Config.MaxRangeForDisabled) if (distance > TShock.Config.MaxRangeForDisabled)
@ -793,10 +804,11 @@ namespace TShockAPI
return true; 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 lastTileX = (int) (args.Player.LastNetPosition.X/16f);
int lastTileY = (int)(args.Player.LastNetPosition.Y / 16f); int lastTileY = (int) (args.Player.LastNetPosition.Y/16f);
if (!args.Player.Teleport(lastTileX, lastTileY + 3)) if (!args.Player.Teleport(lastTileX, lastTileY + 3))
{ {
args.Player.SendMessage("You got stuck in a solid object, Sent to spawn point."); args.Player.SendMessage("You got stuck in a solid object, Sent to spawn point.");
@ -809,11 +821,14 @@ namespace TShockAPI
if ((control & 32) == 32) 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; control -= 32;
args.Player.Disable(); 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);
} }
} }
@ -821,7 +836,7 @@ namespace TShockAPI
args.TPlayer.position = pos; args.TPlayer.position = pos;
args.TPlayer.velocity = vel; args.TPlayer.velocity = vel;
args.TPlayer.oldVelocity = args.TPlayer.velocity; args.TPlayer.oldVelocity = args.TPlayer.velocity;
args.TPlayer.fallStart = (int)(pos.Y / 16f); args.TPlayer.fallStart = (int) (pos.Y/16f);
args.TPlayer.controlUp = false; args.TPlayer.controlUp = false;
args.TPlayer.controlDown = false; args.TPlayer.controlDown = false;
args.TPlayer.controlLeft = false; args.TPlayer.controlLeft = false;
@ -857,7 +872,7 @@ namespace TShockAPI
{ {
args.TPlayer.direction = 1; args.TPlayer.direction = 1;
} }
NetMessage.SendData((int)PacketTypes.PlayerUpdate, -1, args.Player.Index, "", args.Player.Index); NetMessage.SendData((int) PacketTypes.PlayerUpdate, -1, args.Player.Index, "", args.Player.Index);
return true; return true;
} }
@ -983,7 +998,7 @@ namespace TShockAPI
var dmg = args.Data.ReadInt16(); var dmg = args.Data.ReadInt16();
var pvp = args.Data.ReadInt8() == 0; var pvp = args.Data.ReadInt8() == 0;
int textlength = (int)(args.Data.Length - args.Data.Position - 1); int textlength = (int) (args.Data.Length - args.Data.Position - 1);
string deathtext = ""; string deathtext = "";
if (textlength > 0) if (textlength > 0)
{ {
@ -1042,14 +1057,16 @@ namespace TShockAPI
bucket = 2; 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.Disable();
args.Player.SendTileSquare(tileX, tileY); args.Player.SendTileSquare(tileX, tileY);
return true; 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.Disable();
args.Player.SendTileSquare(tileX, tileY); args.Player.SendTileSquare(tileX, tileY);
@ -1236,19 +1253,22 @@ namespace TShockAPI
if (!args.Player.Group.HasPermission(Permissions.movenpc)) if (!args.Player.Group.HasPermission(Permissions.movenpc))
{ {
args.Player.SendMessage("You do not have permission to relocate NPCs.", Color.Red); 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; return true;
} }
if (TShock.CheckTilePermission(args.Player, x, y)) 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; return true;
} }
if (TShock.CheckRangePermission(args.Player, x, y)) 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 true;
} }
return false; return false;
@ -1304,7 +1324,7 @@ namespace TShockAPI
return false; return false;
} }
if (TShock.CheckRangePermission(args.Player, (int)(pos.X / 16f), (int)(pos.Y / 16f))) if (TShock.CheckRangePermission(args.Player, (int) (pos.X/16f), (int) (pos.Y/16f)))
{ {
args.Player.SendData(PacketTypes.ItemDrop, "", id); args.Player.SendData(PacketTypes.ItemDrop, "", id);
return true; return true;
@ -1335,7 +1355,7 @@ namespace TShockAPI
var pvp = args.Data.ReadInt8(); var pvp = args.Data.ReadInt8();
var crit = args.Data.ReadInt8(); var crit = args.Data.ReadInt8();
int textlength = (int)(args.Data.Length - args.Data.Position - 1); int textlength = (int) (args.Data.Length - args.Data.Position - 1);
string deathtext = ""; string deathtext = "";
if (textlength > 0) if (textlength > 0)
{ {
@ -1418,7 +1438,9 @@ namespace TShockAPI
return true; 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); args.Player.SendData(PacketTypes.NpcUpdate, "", id);
return true; return true;
@ -1474,7 +1496,8 @@ namespace TShockAPI
if (buff == 10) 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; buff = 0;
else if (TShock.Config.DisableInvisPvP && args.TPlayer.hostile) else if (TShock.Config.DisableInvisPvP && args.TPlayer.hostile)
buff = 0; buff = 0;
@ -1490,7 +1513,7 @@ namespace TShockAPI
args.TPlayer.buffTime[i] = 0; args.TPlayer.buffTime[i] = 0;
} }
} }
NetMessage.SendData((int)PacketTypes.PlayerBuff, -1, args.Player.Index, "", args.Player.Index); NetMessage.SendData((int) PacketTypes.PlayerBuff, -1, args.Player.Index, "", args.Player.Index);
return true; return true;
} }
} }

View file

@ -75,12 +75,13 @@ namespace TShockAPI
{ {
permissions.Add(permission); permissions.Add(permission);
} }
public void SetPermission( List<string> permission)
public void SetPermission(List<string> permission)
{ {
permissions.Clear(); permissions.Clear();
foreach( string s in permission ) foreach (string s in permission)
{ {
permissions.Add( s ); permissions.Add(s);
} }
} }
} }
@ -90,12 +91,11 @@ namespace TShockAPI
public SuperAdminGroup() public SuperAdminGroup()
: base("superadmin") : base("superadmin")
{ {
R = (byte)TShock.Config.SuperAdminChatRGB[0]; R = (byte) TShock.Config.SuperAdminChatRGB[0];
G = (byte)TShock.Config.SuperAdminChatRGB[1]; G = (byte) TShock.Config.SuperAdminChatRGB[1];
B = (byte)TShock.Config.SuperAdminChatRGB[2]; B = (byte) TShock.Config.SuperAdminChatRGB[2];
Prefix = TShock.Config.SuperAdminChatPrefix; Prefix = TShock.Config.SuperAdminChatPrefix;
Suffix = TShock.Config.SuperAdminChatSuffix; Suffix = TShock.Config.SuperAdminChatSuffix;
} }
public override bool HasPermission(string permission) public override bool HasPermission(string permission)

View file

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

View file

@ -10,15 +10,16 @@ namespace TShockAPI.Net
{ {
get { throw new NotImplementedException("Msg ID not implemented"); } get { throw new NotImplementedException("Msg ID not implemented"); }
} }
public void PackFull(Stream stream) public void PackFull(Stream stream)
{ {
long start = stream.Position; long start = stream.Position;
stream.WriteInt32(1); stream.WriteInt32(1);
stream.WriteInt8((byte)ID); stream.WriteInt8((byte) ID);
Pack(stream); Pack(stream);
long end = stream.Position; long end = stream.Position;
stream.Position = start; stream.Position = start;
stream.WriteInt32((int)(end - start) - 4); stream.WriteInt32((int) (end - start) - 4);
stream.Position = end; stream.Position = end;
} }

View file

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

View file

@ -34,9 +34,20 @@ namespace TShockAPI.Net
public bool Lava { get; set; } public bool Lava { get; set; }
public bool Wire { get; set; } public bool Wire { get; set; }
public bool HasWall { get { return Wall > 0; } } public bool HasWall
public bool HasLiquid { get { return Liquid > 0; } } {
public bool FrameImportant { get { return Main.tileFrameImportant[Type]; } } get { return Wall > 0; }
}
public bool HasLiquid
{
get { return Liquid > 0; }
}
public bool FrameImportant
{
get { return Main.tileFrameImportant[Type]; }
}
public NetTile() public NetTile()
{ {
@ -72,7 +83,7 @@ namespace TShockAPI.Net
if (Wire) if (Wire)
flags |= TileFlags.Wire; flags |= TileFlags.Wire;
stream.WriteInt8((byte)flags); stream.WriteInt8((byte) flags);
if (Active) if (Active)
{ {
@ -96,7 +107,7 @@ namespace TShockAPI.Net
public void Unpack(Stream stream) public void Unpack(Stream stream)
{ {
var flags = (TileFlags)stream.ReadInt8(); var flags = (TileFlags) stream.ReadInt8();
Active = flags.HasFlag(TileFlags.Active); Active = flags.HasFlag(TileFlags.Active);
if (Active) if (Active)

View file

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

View file

@ -7,14 +7,11 @@ namespace TShockAPI.Net
{ {
public override PacketTypes ID public override PacketTypes ID
{ {
get get { return PacketTypes.PlayerSpawn; }
{
return PacketTypes.PlayerSpawn;
}
} }
public int TileX { get; set; } public int TileX { get; set; }
public int TileY {get;set;} public int TileY { get; set; }
public byte PlayerIndex { get; set; } public byte PlayerIndex { get; set; }
public override void Pack(Stream stream) public override void Pack(Stream stream)

View file

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

View file

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

View file

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

View file

@ -28,7 +28,7 @@ using Terraria;
namespace TShockAPI namespace TShockAPI
{ {
class RconHandler internal class RconHandler
{ {
public static string Password = ""; public static string Password = "";
private static DateTime LastRequest; private static DateTime LastRequest;
@ -125,12 +125,11 @@ namespace TShockAPI
Log.Error(e.ToString()); Log.Error(e.ToString());
} }
} }
} }
private static string SendPacket(byte[] bytes, string hostname, int port) private static string SendPacket(byte[] bytes, string hostname, int port)
{ {
var response = Encoding.UTF8.GetString(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }) + "disconnect"; var response = Encoding.UTF8.GetString(new byte[] {0xFF, 0xFF, 0xFF, 0xFF}) + "disconnect";
try try
{ {
var EP = new IPEndPoint(IPAddress.Any, port); var EP = new IPEndPoint(IPAddress.Any, port);
@ -157,7 +156,8 @@ namespace TShockAPI
var print = true; var print = true;
if ((DateTime.Now - LastRequest).Milliseconds >= 100) 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)) if (!string.IsNullOrEmpty(Password))
{ {
@ -202,7 +202,9 @@ namespace TShockAPI
if (packetstring.Split(' ').Length == 2) if (packetstring.Split(' ').Length == 2)
challenge = packetstring.Split(' ')[1]; challenge = packetstring.Split(' ')[1];
response = "infoResponse\n"; 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.Config.ServerName, Main.worldName, Main.maxNetPlayers,
TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots, TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots,
TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum, TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum,
@ -221,7 +223,8 @@ namespace TShockAPI
if (packetstring.Split(' ').Length == 2) if (packetstring.Split(' ').Length == 2)
challenge = packetstring.Split(' ')[1]; challenge = packetstring.Split(' ')[1];
response = "statusResponse\n"; 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.Config.ServerName, Main.worldName, Main.maxNetPlayers,
TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots, TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots,
TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum, TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum,
@ -264,7 +267,8 @@ namespace TShockAPI
if (player != null && player.Active) if (player != null && player.Active)
{ {
count++; 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)); TSPlayer.Server.SendMessage(string.Format("{0} players connected.", count));
@ -279,7 +283,9 @@ namespace TShockAPI
if (player != null && player.Active) if (player != null && player.Active)
{ {
count++; 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,15 +305,14 @@ namespace TShockAPI
if (!Commands.HandleCommand(TSPlayer.Server, text)) if (!Commands.HandleCommand(TSPlayer.Server, text))
return "Invalid command."; return "Invalid command.";
} }
else else if (!Commands.HandleCommand(TSPlayer.Server, "/" + text))
if (!Commands.HandleCommand(TSPlayer.Server, "/" + text))
return "Invalid command."; return "Invalid command.";
return ""; return "";
} }
private static byte[] ConstructPacket(string response, bool print) private static byte[] ConstructPacket(string response, bool print)
{ {
var oob = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF }; var oob = new byte[] {0xFF, 0xFF, 0xFF, 0xFF};
using (var stream = new MemoryStream()) using (var stream = new MemoryStream())
{ {
stream.WriteBytes(oob); stream.WriteBytes(oob);
@ -315,9 +320,9 @@ namespace TShockAPI
stream.WriteBytes(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response))); stream.WriteBytes(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response)));
else else
stream.WriteBytes(Encoding.UTF8.GetBytes(response)); stream.WriteBytes(Encoding.UTF8.GetBytes(response));
var trimmedpacket = new byte[(int)stream.Length]; var trimmedpacket = new byte[(int) stream.Length];
var packet = stream.GetBuffer(); var packet = stream.GetBuffer();
Array.Copy(packet, trimmedpacket, (int)stream.Length); Array.Copy(packet, trimmedpacket, (int) stream.Length);
return trimmedpacket; return trimmedpacket;
} }
} }
@ -368,6 +373,7 @@ namespace TShockAPI
} }
#region ParseParams #region ParseParams
private static List<String> ParseParameters(string str) private static List<String> ParseParameters(string str)
{ {
var ret = new List<string>(); var ret = new List<string>();
@ -424,6 +430,7 @@ namespace TShockAPI
return ret; return ret;
} }
private static char GetEscape(char c) private static char GetEscape(char c)
{ {
switch (c) switch (c)
@ -438,10 +445,12 @@ namespace TShockAPI
return c; return c;
} }
} }
private static bool IsWhiteSpace(char c) private static bool IsWhiteSpace(char c)
{ {
return c == ' ' || c == '\t' || c == '\n'; return c == ' ' || c == '\t' || c == '\n';
} }
#endregion #endregion
} }
} }

View file

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

View file

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

View file

@ -8,10 +8,10 @@ using TShockAPI.DB;
namespace TShockAPI namespace TShockAPI
{ {
public class RestManager public class RestManager
{ {
private Rest Rest; private Rest Rest;
public RestManager(Rest rest) public RestManager(Rest rest)
{ {
Rest = rest; Rest = rest;
@ -19,41 +19,42 @@ namespace TShockAPI
public void RegisterRestfulCommands() public void RegisterRestfulCommands()
{ {
Rest.Register(new RestCommand("/status", Status) { RequiresToken = false }); Rest.Register(new RestCommand("/status", Status) {RequiresToken = false});
Rest.Register(new RestCommand("/tokentest", TokenTest) { RequiresToken = true }); Rest.Register(new RestCommand("/tokentest", TokenTest) {RequiresToken = true});
Rest.Register(new RestCommand("/users/read/{user}/info", UserInfo) { RequiresToken = true }); Rest.Register(new RestCommand("/users/read/{user}/info", UserInfo) {RequiresToken = true});
Rest.Register(new RestCommand("/users/destroy/{user}", UserDestroy) { RequiresToken = true }); Rest.Register(new RestCommand("/users/destroy/{user}", UserDestroy) {RequiresToken = true});
Rest.Register(new RestCommand("/users/update/{user}", UserUpdate) { RequiresToken = true }); Rest.Register(new RestCommand("/users/update/{user}", UserUpdate) {RequiresToken = true});
Rest.Register(new RestCommand("/bans/create", BanCreate) { RequiresToken = true }); Rest.Register(new RestCommand("/bans/create", BanCreate) {RequiresToken = true});
Rest.Register(new RestCommand("/bans/read/{user}/info", BanInfo) { RequiresToken = true }); Rest.Register(new RestCommand("/bans/read/{user}/info", BanInfo) {RequiresToken = true});
Rest.Register(new RestCommand("/bans/destroy/{user}", BanDestroy) { RequiresToken = true }); Rest.Register(new RestCommand("/bans/destroy/{user}", BanDestroy) {RequiresToken = true});
Rest.Register(new RestCommand("/lists/players", UserList) { RequiresToken = true }); Rest.Register(new RestCommand("/lists/players", UserList) {RequiresToken = true});
Rest.Register(new RestCommand("/world/read", WorldRead) { RequiresToken = true }); Rest.Register(new RestCommand("/world/read", WorldRead) {RequiresToken = true});
Rest.Register(new RestCommand("/world/meteor", WorldMeteor) { RequiresToken = true }); Rest.Register(new RestCommand("/world/meteor", WorldMeteor) {RequiresToken = true});
Rest.Register(new RestCommand("/world/bloodmoon/{bool}", WorldBloodmoon) { RequiresToken = true }); Rest.Register(new RestCommand("/world/bloodmoon/{bool}", WorldBloodmoon) {RequiresToken = true});
Rest.Register(new RestCommand("/players/read/{player}", PlayerRead) { RequiresToken = true }); Rest.Register(new RestCommand("/players/read/{player}", PlayerRead) {RequiresToken = true});
Rest.Register(new RestCommand("/players/{player}/kick", PlayerKick) { RequiresToken = true }); Rest.Register(new RestCommand("/players/{player}/kick", PlayerKick) {RequiresToken = true});
Rest.Register(new RestCommand("/players/{player}/ban", PlayerBan) { RequiresToken = true }); Rest.Register(new RestCommand("/players/{player}/ban", PlayerBan) {RequiresToken = true});
//RegisterExamples(); //RegisterExamples();
} }
#region RestMethods #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) if (TShock.Config.EnableTokenEndpointAuthentication)
return new RestObject("403") { Error = "Server settings require a token for this API call." }; return new RestObject("403") {Error = "Server settings require a token for this API call."};
var activeplayers = Main.player.Where(p => p != null && p.active).ToList(); var activeplayers = Main.player.Where(p => p != null && p.active).ToList();
string currentPlayers = string.Join(", ", activeplayers.Select(p => p.name)); string currentPlayers = string.Join(", ", activeplayers.Select(p => p.name));
@ -71,7 +72,7 @@ namespace TShockAPI
#region RestUserMethods #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(); var activeplayers = Main.player.Where(p => p != null && p.active).ToList();
string currentPlayers = string.Join(", ", activeplayers.Select(p => p.name)); string currentPlayers = string.Join(", ", activeplayers.Select(p => p.name));
@ -80,7 +81,7 @@ namespace TShockAPI
return ret; return ret;
} }
object UserUpdate(RestVerbs verbs, IParameterCollection parameters) private object UserUpdate(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
var password = parameters["password"]; var password = parameters["password"];
@ -117,12 +118,12 @@ namespace TShockAPI
return returnBlock; return returnBlock;
} }
object UserDestroy(RestVerbs verbs, IParameterCollection parameters) private object UserDestroy(RestVerbs verbs, IParameterCollection parameters)
{ {
var user = TShock.Users.GetUserByName(verbs["user"]); var user = TShock.Users.GetUserByName(verbs["user"]);
if (user == null) if (user == null)
{ {
return new Dictionary<string, string> { { "status", "400" }, { "error", "The specified user account does not exist." } }; return new Dictionary<string, string> {{"status", "400"}, {"error", "The specified user account does not exist."}};
} }
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
try try
@ -140,12 +141,12 @@ namespace TShockAPI
return returnBlock; return returnBlock;
} }
object UserInfo(RestVerbs verbs, IParameterCollection parameters) private object UserInfo(RestVerbs verbs, IParameterCollection parameters)
{ {
var user = TShock.Users.GetUserByName(verbs["user"]); var user = TShock.Users.GetUserByName(verbs["user"]);
if (user == null) if (user == null)
{ {
return new Dictionary<string, string> { { "status", "400" }, { "error", "The specified user account does not exist." } }; return new Dictionary<string, string> {{"status", "400"}, {"error", "The specified user account does not exist."}};
} }
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
@ -159,7 +160,7 @@ namespace TShockAPI
#region RestBanMethods #region RestBanMethods
object BanCreate(RestVerbs verbs, IParameterCollection parameters) private object BanCreate(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
var ip = parameters["ip"]; var ip = parameters["ip"];
@ -203,7 +204,7 @@ namespace TShockAPI
return returnBlock; return returnBlock;
} }
object BanDestroy(RestVerbs verbs, IParameterCollection parameters) private object BanDestroy(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
@ -225,7 +226,7 @@ namespace TShockAPI
if (ban == null) if (ban == null)
{ {
return new Dictionary<string, string> { { "status", "400" }, { "error", "The specified ban does not exist." } }; return new Dictionary<string, string> {{"status", "400"}, {"error", "The specified ban does not exist."}};
} }
try try
@ -243,7 +244,7 @@ namespace TShockAPI
return returnBlock; return returnBlock;
} }
object BanInfo(RestVerbs verbs, IParameterCollection parameters) private object BanInfo(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
@ -265,7 +266,7 @@ namespace TShockAPI
if (ban == null) if (ban == null)
{ {
return new Dictionary<string, string> { { "status", "400" }, { "error", "The specified ban does not exist." } }; return new Dictionary<string, string> {{"status", "400"}, {"error", "The specified ban does not exist."}};
} }
returnBlock.Add("status", "200"); returnBlock.Add("status", "200");
@ -278,7 +279,8 @@ namespace TShockAPI
#endregion #endregion
#region RestWorldMethods #region RestWorldMethods
object WorldRead(RestVerbs verbs, IParameterCollection parameters)
private object WorldRead(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, object>(); var returnBlock = new Dictionary<string, object>();
returnBlock.Add("status", "200"); returnBlock.Add("status", "200");
@ -291,7 +293,7 @@ namespace TShockAPI
return returnBlock; return returnBlock;
} }
object WorldMeteor(RestVerbs verbs, IParameterCollection parameters) private object WorldMeteor(RestVerbs verbs, IParameterCollection parameters)
{ {
WorldGen.dropMeteor(); WorldGen.dropMeteor();
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
@ -300,7 +302,7 @@ namespace TShockAPI
return returnBlock; return returnBlock;
} }
object WorldBloodmoon(RestVerbs verbs, IParameterCollection parameters) private object WorldBloodmoon(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, string>(); var returnBlock = new Dictionary<string, string>();
var bloodmoonVerb = verbs["bool"]; var bloodmoonVerb = verbs["bool"];
@ -322,10 +324,12 @@ namespace TShockAPI
returnBlock.Add("response", "Blood Moon has been set to " + bloodmoon); returnBlock.Add("response", "Blood Moon has been set to " + bloodmoon);
return returnBlock; return returnBlock;
} }
#endregion #endregion
#region RestPlayerMethods #region RestPlayerMethods
object PlayerRead(RestVerbs verbs, IParameterCollection parameters)
private object PlayerRead(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, object>(); var returnBlock = new Dictionary<string, object>();
var playerParam = parameters["player"]; var playerParam = parameters["player"];
@ -355,7 +359,8 @@ namespace TShockAPI
} }
return returnBlock; return returnBlock;
} }
object PlayerKick(RestVerbs verbs, IParameterCollection parameters)
private object PlayerKick(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, object>(); var returnBlock = new Dictionary<string, object>();
var playerParam = parameters["player"]; var playerParam = parameters["player"];
@ -380,7 +385,8 @@ namespace TShockAPI
} }
return returnBlock; return returnBlock;
} }
object PlayerBan(RestVerbs verbs, IParameterCollection parameters)
private object PlayerBan(RestVerbs verbs, IParameterCollection parameters)
{ {
var returnBlock = new Dictionary<string, object>(); var returnBlock = new Dictionary<string, object>();
var playerParam = parameters["player"]; var playerParam = parameters["player"];
@ -406,28 +412,31 @@ namespace TShockAPI
} }
return returnBlock; return returnBlock;
} }
#endregion #endregion
#region RestExampleMethods #region RestExampleMethods
public void RegisterExamples() public void RegisterExamples()
{ {
Rest.Register(new RestCommand("/HelloWorld/name/{username}", UserTest) { RequiresToken = false }); Rest.Register(new RestCommand("/HelloWorld/name/{username}", UserTest) {RequiresToken = false});
Rest.Register(new RestCommand("/wizard/{username}", Wizard) { RequiresToken = false }); Rest.Register(new RestCommand("/wizard/{username}", Wizard) {RequiresToken = false});
} }
//The Wizard example, for demonstrating the response convention: //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>(); var returnBack = new Dictionary<string, string>();
returnBack.Add("status", "200"); //Keep this in everything, 200 = ok, etc. Standard http status codes. 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("error", "(If this failed, you would have a different status code and provide the error object.)");
returnBack.Add("Verified Wizard", "You're a wizard, " + verbs["username"]); //Outline any api calls and possible responses in some form of documentation somewhere //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; return returnBack;
} }
//http://127.0.0.1:8080/HelloWorld/name/{username}?type=status //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 ret = new Dictionary<string, string>();
var type = parameters["type"]; var type = parameters["type"];
@ -443,6 +452,7 @@ namespace TShockAPI
} }
return null; return null;
} }
#endregion #endregion
} }
} }

View file

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

View file

@ -13,19 +13,21 @@ namespace Rests
/// <param name="password">Password to verify</param> /// <param name="password">Password to verify</param>
/// <returns>Returning a restobject with a null error means a successful verification.</returns> /// <returns>Returning a restobject with a null error means a successful verification.</returns>
public delegate RestObject VerifyD(string username, string password); public delegate RestObject VerifyD(string username, string password);
public class SecureRest : Rest public class SecureRest : Rest
{ {
public Dictionary<string, object> Tokens { get; protected set; } public Dictionary<string, object> Tokens { get; protected set; }
public event VerifyD Verify; public event VerifyD Verify;
public SecureRest(IPAddress ip, int port) public SecureRest(IPAddress ip, int port)
: base(ip, port) : base(ip, port)
{ {
Tokens = new Dictionary<string, object>(); Tokens = new Dictionary<string, object>();
Register(new RestCommand("/token/create/{username}/{password}", NewToken) { RequiresToken = false }); Register(new RestCommand("/token/create/{username}/{password}", NewToken) {RequiresToken = false});
Register(new RestCommand("/token/destroy/{token}", DestroyToken) { RequiresToken = true }); 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"]; var token = verbs["token"];
try try
@ -34,12 +36,14 @@ namespace Rests
} }
catch (Exception) 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 user = verbs["username"];
var pass = verbs["password"]; var pass = verbs["password"];
@ -49,7 +53,8 @@ namespace Rests
obj = Verify(user, pass); obj = Verify(user, pass);
if (obj == null) 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) if (obj.Error != null)
return obj; return obj;
@ -70,18 +75,25 @@ namespace Rests
} }
protected override object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms) protected override object ExecuteCommand(RestCommand cmd, RestVerbs verbs, IParameterCollection parms)
{ {
if (cmd.RequiresToken) if (cmd.RequiresToken)
{ {
var strtoken = parms["token"]; var strtoken = parms["token"];
if (strtoken == null) 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; object token;
if (!Tokens.TryGetValue(strtoken, out 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); return base.ExecuteCommand(cmd, verbs, parms);
} }

View file

@ -8,9 +8,9 @@ namespace TShockAPI
{ {
public class StatTracker public class StatTracker
{ {
Utils Utils = TShock.Utils; private Utils Utils = TShock.Utils;
public DateTime lastcheck = DateTime.MinValue; public DateTime lastcheck = DateTime.MinValue;
readonly int checkinFrequency = 5; private readonly int checkinFrequency = 5;
public void checkin() public void checkin()
{ {
@ -57,11 +57,17 @@ namespace TShockAPI
string response; string response;
if (TShock.Config.DisablePlayerCountReporting) 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 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"); Log.ConsoleInfo("Stat Tracker: " + response + "\n");
} }

View file

@ -61,7 +61,7 @@ namespace TShockAPI
public bool TPAllow = true; public bool TPAllow = true;
public bool mute; public bool mute;
public bool TpLock; public bool TpLock;
Player FakePlayer; private Player FakePlayer;
public bool RequestedSection; public bool RequestedSection;
public DateTime LastDeath { get; set; } public DateTime LastDeath { get; set; }
public bool Dead; public bool Dead;
@ -79,9 +79,14 @@ namespace TShockAPI
{ {
get { return Index >= 0 && Index < Main.maxNetPlayers && Main.player[Index] != null; } get { return Index >= 0 && Index < Main.maxNetPlayers && Main.player[Index] != null; }
} }
public bool ConnectionAlive 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 public int State
@ -95,56 +100,61 @@ namespace TShockAPI
get get
{ {
if (string.IsNullOrEmpty(CacheIP)) 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 else
return CacheIP; return CacheIP;
} }
} }
/// <summary> /// <summary>
/// Terraria Player /// Terraria Player
/// </summary> /// </summary>
public Player TPlayer public Player TPlayer
{ {
get get { return FakePlayer ?? Main.player[Index]; }
{
return FakePlayer ?? Main.player[Index];
}
} }
public string Name public string Name
{ {
get { return TPlayer.name; } get { return TPlayer.name; }
} }
public bool Active public bool Active
{ {
get { return TPlayer != null && TPlayer.active; } get { return TPlayer != null && TPlayer.active; }
} }
public int Team public int Team
{ {
get { return TPlayer.team; } get { return TPlayer.team; }
} }
public float X public float X
{ {
get get { return RealPlayer ? TPlayer.position.X : Main.spawnTileX*16; }
{ }
return RealPlayer ? TPlayer.position.X : Main.spawnTileX * 16;
}
}
public float Y public float Y
{ {
get get { return RealPlayer ? TPlayer.position.Y : Main.spawnTileY*16; }
{
return RealPlayer ? TPlayer.position.Y : Main.spawnTileY * 16;
}
} }
public int TileX public int TileX
{ {
get { return (int)(X / 16); } get { return (int) (X/16); }
} }
public int TileY public int TileY
{ {
get { return (int)(Y / 16); } get { return (int) (Y/16); }
} }
public bool InventorySlotAvailable public bool InventorySlotAvailable
{ {
get get
@ -178,7 +188,7 @@ namespace TShockAPI
TilesDestroyed = new Dictionary<Vector2, TileData>(); TilesDestroyed = new Dictionary<Vector2, TileData>();
TilesCreated = new Dictionary<Vector2, TileData>(); TilesCreated = new Dictionary<Vector2, TileData>();
Index = -1; Index = -1;
FakePlayer = new Player { name = playerName, whoAmi = -1 }; FakePlayer = new Player {name = playerName, whoAmi = -1};
Group = new Group(TShock.Config.DefaultGuestGroupName); Group = new Group(TShock.Config.DefaultGuestGroupName);
} }
@ -197,22 +207,22 @@ namespace TShockAPI
} }
void SendWorldInfo(int tilex, int tiley, bool fakeid) private void SendWorldInfo(int tilex, int tiley, bool fakeid)
{ {
using (var ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
var msg = new WorldInfoMsg var msg = new WorldInfoMsg
{ {
Time = (int)Main.time, Time = (int) Main.time,
DayTime = Main.dayTime, DayTime = Main.dayTime,
MoonPhase = (byte)Main.moonPhase, MoonPhase = (byte) Main.moonPhase,
BloodMoon = Main.bloodMoon, BloodMoon = Main.bloodMoon,
MaxTilesX = Main.maxTilesX, MaxTilesX = Main.maxTilesX,
MaxTilesY = Main.maxTilesY, MaxTilesY = Main.maxTilesY,
SpawnX = tilex, SpawnX = tilex,
SpawnY = tiley, SpawnY = tiley,
WorldSurface = (int)Main.worldSurface, WorldSurface = (int) Main.worldSurface,
RockLayer = (int)Main.rockLayer, RockLayer = (int) Main.rockLayer,
//Sending a fake world id causes the client to not be able to find a stored spawnx/y. //Sending a fake world id causes the client to not be able to find a stored spawnx/y.
//This fixes the bed spawn point bug. With a fake world id it wont be able to find the bed spawn. //This fixes the bed spawn point bug. With a fake world id it wont be able to find the bed spawn.
WorldID = !fakeid ? Main.worldID : -1, WorldID = !fakeid ? Main.worldID : -1,
@ -267,7 +277,7 @@ namespace TShockAPI
{ {
var msg = new SpawnMsg var msg = new SpawnMsg
{ {
PlayerIndex = (byte)Index, PlayerIndex = (byte) Index,
TileX = tilex, TileX = tilex,
TileY = tiley TileY = tiley
}; };
@ -282,8 +292,8 @@ namespace TShockAPI
{ {
var msg = new ProjectileRemoveMsg var msg = new ProjectileRemoveMsg
{ {
Index = (short)index, Index = (short) index,
Owner = (byte)owner Owner = (byte) owner
}; };
msg.PackFull(ms); msg.PackFull(ms);
SendRawData(ms.ToArray()); SendRawData(ms.ToArray());
@ -294,7 +304,7 @@ namespace TShockAPI
{ {
try try
{ {
int num = (size - 1) / 2; int num = (size - 1)/2;
SendData(PacketTypes.TileSendSquare, "", size, (x - num), (y - num)); SendData(PacketTypes.TileSendSquare, "", size, (x - num), (y - num));
return true; return true;
} }
@ -307,16 +317,17 @@ namespace TShockAPI
public virtual void GiveItem(int type, string name, int width, int height, int stack, int prefix = 0) public virtual void GiveItem(int type, string name, int width, int height, int stack, int prefix = 0)
{ {
int itemid = Item.NewItem((int)X, (int)Y, width, height, type, stack, true, prefix); int itemid = Item.NewItem((int) X, (int) Y, width, height, type, stack, true, prefix);
// This is for special pickaxe/hammers/swords etc // This is for special pickaxe/hammers/swords etc
Main.item[itemid].SetDefaults(name); Main.item[itemid].SetDefaults(name);
// The set default overrides the wet and stack set by NewItem // 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].stack = stack;
Main.item[itemid].owner = Index; Main.item[itemid].owner = Index;
Main.item[itemid].prefix = (byte) prefix; Main.item[itemid].prefix = (byte) prefix;
NetMessage.SendData((int)PacketTypes.ItemDrop, -1, -1, "", itemid, 0f, 0f, 0f); NetMessage.SendData((int) PacketTypes.ItemDrop, -1, -1, "", itemid, 0f, 0f, 0f);
NetMessage.SendData((int)PacketTypes.ItemOwner, -1, -1, "", itemid, 0f, 0f, 0f); NetMessage.SendData((int) PacketTypes.ItemOwner, -1, -1, "", itemid, 0f, 0f, 0f);
} }
public virtual void SendMessage(string msg) public virtual void SendMessage(string msg)
@ -336,7 +347,8 @@ namespace TShockAPI
public virtual void DamagePlayer(int damage) 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) public virtual void SetTeam(int team)
@ -355,7 +367,7 @@ namespace TShockAPI
public virtual void Whoopie(object time) public virtual void Whoopie(object time)
{ {
var time2 = (int)time; var time2 = (int) time;
var launch = DateTime.UtcNow; var launch = DateTime.UtcNow;
var startname = Name; var startname = Name;
SendMessage("You are now being annoyed.", Color.Red); SendMessage("You are now being annoyed.", Color.Red);
@ -375,12 +387,13 @@ namespace TShockAPI
} }
//Todo: Separate this into a few functions. SendTo, SendToAll, etc //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) if (RealPlayer && !ConnectionAlive)
return; return;
NetMessage.SendData((int)msgType, Index, -1, text, number, number2, number3, number4, number5); NetMessage.SendData((int) msgType, Index, -1, text, number, number2, number3, number4, number5);
} }
public virtual bool SendRawData(byte[] data) public virtual bool SendRawData(byte[] data)
@ -432,18 +445,20 @@ namespace TShockAPI
{ {
Main.dayTime = dayTime; Main.dayTime = dayTime;
Main.time = time; Main.time = time;
NetMessage.SendData((int)PacketTypes.TimeSet, -1, -1, "", 0, 0, Main.sunModY, Main.moonModY); NetMessage.SendData((int) PacketTypes.TimeSet, -1, -1, "", 0, 0, Main.sunModY, Main.moonModY);
NetMessage.syncPlayers(); 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++) for (int i = 0; i < amount; i++)
{ {
int spawnTileX; int spawnTileX;
int spawnTileY; int spawnTileY;
TShock.Utils.GetRandomClearTileWithInRange(startTileX, startTileY, tileXRange, tileYRange, out spawnTileX, out spawnTileY); TShock.Utils.GetRandomClearTileWithInRange(startTileX, startTileY, tileXRange, tileYRange, out spawnTileX,
int npcid = NPC.NewNPC(spawnTileX * 16, spawnTileY * 16, type, 0); out spawnTileY);
int npcid = NPC.NewNPC(spawnTileX*16, spawnTileY*16, type, 0);
// This is for special slimes // This is for special slimes
Main.npc[npcid].SetDefaults(name); Main.npc[npcid].SetDefaults(name);
} }
@ -452,7 +467,7 @@ namespace TShockAPI
public void StrikeNPC(int npcid, int damage, float knockBack, int hitDirection) public void StrikeNPC(int npcid, int damage, float knockBack, int hitDirection)
{ {
Main.npc[npcid].StrikeNPC(damage, knockBack, hitDirection); Main.npc[npcid].StrikeNPC(damage, knockBack, hitDirection);
NetMessage.SendData((int)PacketTypes.NpcStrike, -1, -1, "", npcid, damage, knockBack, hitDirection); NetMessage.SendData((int) PacketTypes.NpcStrike, -1, -1, "", npcid, damage, knockBack, hitDirection);
} }
public void RevertTiles(Dictionary<Vector2, TileData> tiles) public void RevertTiles(Dictionary<Vector2, TileData> tiles)
@ -460,12 +475,12 @@ namespace TShockAPI
// Update Main.Tile first so that when tile sqaure is sent it is correct // Update Main.Tile first so that when tile sqaure is sent it is correct
foreach (KeyValuePair<Vector2, TileData> entry in tiles) foreach (KeyValuePair<Vector2, TileData> entry in tiles)
{ {
Main.tile[(int)entry.Key.X, (int)entry.Key.Y].Data = entry.Value; Main.tile[(int) entry.Key.X, (int) entry.Key.Y].Data = entry.Value;
} }
// Send all players updated tile sqaures // Send all players updated tile sqaures
foreach (Vector2 coords in tiles.Keys) foreach (Vector2 coords in tiles.Keys)
{ {
All.SendTileSquare((int)coords.X, (int)coords.Y, 3); All.SendTileSquare((int) coords.X, (int) coords.Y, 3);
} }
} }
} }
@ -485,7 +500,7 @@ namespace TShockAPI
} }
this.inventory[0].netID = -15; this.inventory[0].netID = -15;
this.inventory[0].stack = 1; this.inventory[0].stack = 1;
if(player.TPlayer.inventory[0] != null && player.TPlayer.inventory[0].netID == -15) if (player.TPlayer.inventory[0] != null && player.TPlayer.inventory[0].netID == -15)
this.inventory[0].prefix = player.TPlayer.inventory[0].prefix; this.inventory[0].prefix = player.TPlayer.inventory[0].prefix;
this.inventory[1].netID = -13; this.inventory[1].netID = -13;
this.inventory[1].stack = 1; this.inventory[1].stack = 1;

View file

@ -48,7 +48,7 @@ namespace TShockAPI
public class TShock : TerrariaPlugin public class TShock : TerrariaPlugin
{ {
public static readonly Version VersionNum = Assembly.GetExecutingAssembly().GetName().Version; 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"; public static string SavePath = "tshock";
@ -71,6 +71,7 @@ namespace TShockAPI
public static RestManager RestManager; public static RestManager RestManager;
public static Utils Utils = new Utils(); public static Utils Utils = new Utils();
public static StatTracker StatTracker = new StatTracker(); public static StatTracker StatTracker = new StatTracker();
/// <summary> /// <summary>
/// Called after TShock is initialized. Useful for plugins that needs hooks before tshock but also depend on tshock being loaded. /// Called after TShock is initialized. Useful for plugins that needs hooks before tshock but also depend on tshock being loaded.
/// </summary> /// </summary>
@ -105,7 +106,6 @@ namespace TShockAPI
} }
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")]
public override void Initialize() public override void Initialize()
{ {
@ -125,7 +125,8 @@ namespace TShockAPI
{ {
if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) 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.Delete(Path.Combine(SavePath, "tshock.pid"));
} }
File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString()); File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString());
@ -224,30 +225,34 @@ namespace TShockAPI
Log.Error(ex.ToString()); Log.Error(ex.ToString());
Environment.Exit(1); Environment.Exit(1);
} }
} }
private RestObject RestApi_Verify(string username, string password)
RestObject RestApi_Verify(string username, string password)
{ {
var userAccount = Users.GetUserByName(username); var userAccount = Users.GetUserByName(username);
if (userAccount == null) 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()) 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") 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? return new RestObject("200") {Response = "Successful login"}; //Maybe return some user info too?
} }
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
@ -381,7 +386,7 @@ namespace TShockAPI
{ {
if (!File.Exists(Path.Combine(SavePath, "auth.lck")) && !File.Exists(Path.Combine(SavePath, "authcode.txt"))) if (!File.Exists(Path.Combine(SavePath, "auth.lck")) && !File.Exists(Path.Combine(SavePath, "authcode.txt")))
{ {
var r = new Random((int)DateTime.Now.ToBinary()); var r = new Random((int) DateTime.Now.ToBinary());
AuthToken = r.Next(100000, 10000000); AuthToken = r.Next(100000, 10000000);
Console.ForegroundColor = ConsoleColor.Yellow; Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("TShock Notice: To become SuperAdmin, join the game and type /auth " + AuthToken); Console.WriteLine("TShock Notice: To become SuperAdmin, join the game and type /auth " + AuthToken);
@ -400,7 +405,8 @@ namespace TShockAPI
AuthToken = Convert.ToInt32(tr.ReadLine()); AuthToken = Convert.ToInt32(tr.ReadLine());
} }
Console.ForegroundColor = ConsoleColor.Yellow; 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("To become superadmin, join the game and type /auth " + AuthToken);
Console.WriteLine("This token will display until disabled by verification. (/auth-verify)"); Console.WriteLine("This token will display until disabled by verification. (/auth-verify)");
Console.ForegroundColor = ConsoleColor.Gray; Console.ForegroundColor = ConsoleColor.Gray;
@ -416,12 +422,11 @@ namespace TShockAPI
StatTracker.checkin(); StatTracker.checkin();
FixChestStacks(); FixChestStacks();
} }
private void FixChestStacks() private void FixChestStacks()
{ {
foreach(Chest chest in Main.chest) foreach (Chest chest in Main.chest)
{ {
if (chest != null) if (chest != null)
{ {
@ -470,7 +475,7 @@ namespace TShockAPI
{ {
if (Config.ForceTime != "normal") if (Config.ForceTime != "normal")
{ {
switch(Config.ForceTime) switch (Config.ForceTime)
{ {
case "day": case "day":
TSPlayer.Server.SetTime(true, 27000.0); TSPlayer.Server.SetTime(true, 27000.0);
@ -512,7 +517,7 @@ namespace TShockAPI
{ {
player.TilePlaceThreshold = 0; player.TilePlaceThreshold = 0;
} }
if(player.TileLiquidThreshold >= Config.TileLiquidThreshold) if (player.TileLiquidThreshold >= Config.TileLiquidThreshold)
{ {
player.Disable(); player.Disable();
} }
@ -535,7 +540,8 @@ namespace TShockAPI
string check = "none"; string check = "none";
foreach (Item item in player.TPlayer.inventory) 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; 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(32, 120); //Slow
player.SetBuff(23, 120); //Cursed 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 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) private void OnConnect(int ply, HandledEventArgs handler)
@ -662,7 +670,7 @@ namespace TShockAPI
if (Config.RememberLeavePos) if (Config.RememberLeavePos)
{ {
RememberedPos.InsertLeavePos(tsplr.Name, tsplr.IP, (int)(tsplr.X / 16), (int)(tsplr.Y / 16)); RememberedPos.InsertLeavePos(tsplr.Name, tsplr.IP, (int) (tsplr.X/16), (int) (tsplr.Y/16));
} }
} }
} }
@ -699,7 +707,9 @@ namespace TShockAPI
} }
else if (!tsplr.mute) 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; e.Handled = true;
} }
else if (tsplr.mute) else if (tsplr.mute)
@ -766,7 +776,7 @@ namespace TShockAPI
PacketTypes type = e.MsgID; PacketTypes type = e.MsgID;
Debug.WriteLine("Recv: {0:X}: {2} ({1:XX})", e.Msg.whoAmI, (byte)type, type); Debug.WriteLine("Recv: {0:X}: {2} ({1:XX})", e.Msg.whoAmI, (byte) type, type);
var player = Players[e.Msg.whoAmI]; var player = Players[e.Msg.whoAmI];
if (player == null) if (player == null)
@ -787,7 +797,8 @@ namespace TShockAPI
return; 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; e.Handled = true;
return; return;
@ -827,7 +838,9 @@ namespace TShockAPI
{ {
if (Config.ServerSideInventory) 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) else if (Config.RequireLogin)
{ {
@ -840,7 +853,7 @@ namespace TShockAPI
StartInvasion(); StartInvasion();
} }
player.LastNetPosition = new Vector2(Main.spawnTileX * 16f, Main.spawnTileY * 16f); player.LastNetPosition = new Vector2(Main.spawnTileX*16f, Main.spawnTileY*16f);
if (Config.RememberLeavePos) if (Config.RememberLeavePos)
{ {
@ -864,7 +877,7 @@ namespace TShockAPI
} }
} }
void OnProjectileSetDefaults(SetDefaultsEventArgs<Projectile, int> e) private void OnProjectileSetDefaults(SetDefaultsEventArgs<Projectile, int> e)
{ {
if (e.Info == 43) if (e.Info == 43)
if (Config.DisableTombstones) if (Config.DisableTombstones)
@ -875,12 +888,11 @@ namespace TShockAPI
if (e.Info == 109) if (e.Info == 109)
if (Config.DisableSnowBalls) if (Config.DisableSnowBalls)
e.Object.SetDefaults(0); e.Object.SetDefaults(0);
} }
void OnNpcSetDefaults(SetDefaultsEventArgs<NPC, int> e) private void OnNpcSetDefaults(SetDefaultsEventArgs<NPC, int> e)
{ {
if (Itembans.ItemIsBanned(e.Object.name, null) ) if (Itembans.ItemIsBanned(e.Object.name, null))
{ {
e.Object.SetDefaults(0); e.Object.SetDefaults(0);
} }
@ -900,8 +912,9 @@ namespace TShockAPI
return true; return true;
} }
return SendBytesBufferless(client,bytes); return SendBytesBufferless(client, bytes);
} }
/// <summary> /// <summary>
/// Send bytes to a client ignoring the packet buffer /// Send bytes to a client ignoring the packet buffer
/// </summary> /// </summary>
@ -924,11 +937,11 @@ namespace TShockAPI
return false; return false;
} }
void NetHooks_SendData(SendDataEventArgs e) private void NetHooks_SendData(SendDataEventArgs e)
{ {
if (e.MsgID == PacketTypes.Disconnect) if (e.MsgID == PacketTypes.Disconnect)
{ {
Action<ServerSock,string> senddisconnect = (sock, str) => Action<ServerSock, string> senddisconnect = (sock, str) =>
{ {
if (sock == null || !sock.active) if (sock == null || !sock.active)
return; return;
@ -966,7 +979,7 @@ namespace TShockAPI
e.Handled = true; e.Handled = true;
} }
void OnStartHardMode(HandledEventArgs e) private void OnStartHardMode(HandledEventArgs e)
{ {
if (Config.DisableHardmode) if (Config.DisableHardmode)
e.Handled = true; e.Handled = true;
@ -985,7 +998,7 @@ namespace TShockAPI
} }
else else
{ {
Main.invasionSize = 100 + (Config.InvasionMultiplier * Utils.ActivePlayers()); Main.invasionSize = 100 + (Config.InvasionMultiplier*Utils.ActivePlayers());
} }
Main.invasionWarn = 0; Main.invasionWarn = 0;
@ -1006,7 +1019,7 @@ namespace TShockAPI
KillCount++; KillCount++;
Random r = new Random(); Random r = new Random();
int random = r.Next(5); int random = r.Next(5);
if (KillCount % 100 == 0) if (KillCount%100 == 0)
{ {
switch (random) switch (random)
{ {
@ -1039,12 +1052,14 @@ namespace TShockAPI
return true; 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; 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; return true;
} }
@ -1081,7 +1096,8 @@ namespace TShockAPI
player.SendMessage("You do not have permission to build!", Color.Red); player.SendMessage("You do not have permission to build!", Color.Red);
return true; 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); player.SendMessage("Region protected from changes.", Color.Red);
return true; return true;
@ -1115,12 +1131,13 @@ namespace TShockAPI
Vector2 spawn = new Vector2(Main.spawnTileX, Main.spawnTileY); Vector2 spawn = new Vector2(Main.spawnTileX, Main.spawnTileY);
return Distance(spawn, tile) <= Config.SpawnProtectionRadius; return Distance(spawn, tile) <= Config.SpawnProtectionRadius;
} }
public static float Distance(Vector2 value1, Vector2 value2) public static float Distance(Vector2 value1, Vector2 value2)
{ {
float num2 = value1.X - value2.X; float num2 = value1.X - value2.X;
float num = value1.Y - value2.Y; float num = value1.Y - value2.Y;
float num3 = (num2 * num2) + (num * num); float num3 = (num2*num2) + (num*num);
return (float)Math.Sqrt(num3); return (float) Math.Sqrt(num3);
} }
public static bool HackedHealth(TSPlayer player) public static bool HackedHealth(TSPlayer player)
@ -1150,7 +1167,9 @@ namespace TShockAPI
if (inventory[i].stack > item.maxStack) if (inventory[i].stack > item.maxStack)
{ {
check = true; 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) if (armor[i - 48].stack > item.maxStack)
{ {
check = true; 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) 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; check = false;
} }
@ -1200,7 +1222,8 @@ namespace TShockAPI
item.netDefaults(inventory[i].netID); item.netDefaults(inventory[i].netID);
item.Prefix(inventory[i].prefix); item.Prefix(inventory[i].prefix);
item.AffixName(); 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; check = false;
} }
else if (playerData.inventory[i].prefix != inventory[i].prefix) else if (playerData.inventory[i].prefix != inventory[i].prefix)
@ -1208,7 +1231,8 @@ namespace TShockAPI
item.netDefaults(inventory[i].netID); item.netDefaults(inventory[i].netID);
item.Prefix(inventory[i].prefix); item.Prefix(inventory[i].prefix);
item.AffixName(); 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; check = false;
} }
else if (inventory[i].stack > playerData.inventory[i].stack) else if (inventory[i].stack > playerData.inventory[i].stack)
@ -1216,7 +1240,10 @@ namespace TShockAPI
item.netDefaults(inventory[i].netID); item.netDefaults(inventory[i].netID);
item.Prefix(inventory[i].prefix); item.Prefix(inventory[i].prefix);
item.AffixName(); 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; check = false;
} }
} }
@ -1232,7 +1259,8 @@ namespace TShockAPI
item.netDefaults(armor[i - 48].netID); item.netDefaults(armor[i - 48].netID);
item.Prefix(armor[i - 48].prefix); item.Prefix(armor[i - 48].prefix);
item.AffixName(); 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; check = false;
} }
else if (playerData.inventory[i].prefix != armor[i - 48].prefix) else if (playerData.inventory[i].prefix != armor[i - 48].prefix)
@ -1240,7 +1268,8 @@ namespace TShockAPI
item.netDefaults(armor[i - 48].netID); item.netDefaults(armor[i - 48].netID);
item.Prefix(armor[i - 48].prefix); item.Prefix(armor[i - 48].prefix);
item.AffixName(); 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; check = false;
} }
else if (armor[i - 48].stack > playerData.inventory[i].stack) else if (armor[i - 48].stack > playerData.inventory[i].stack)
@ -1248,7 +1277,10 @@ namespace TShockAPI
item.netDefaults(armor[i - 48].netID); item.netDefaults(armor[i - 48].netID);
item.Prefix(armor[i - 48].prefix); item.Prefix(armor[i - 48].prefix);
item.AffixName(); 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; check = false;
} }
} }

View file

@ -24,14 +24,15 @@ using Newtonsoft.Json;
namespace TShockAPI 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; public static DateTime lastcheck = DateTime.MinValue;
/// <summary> /// <summary>
/// Check once every X minutes. /// Check once every X minutes.
/// </summary> /// </summary>
static readonly int CheckXMinutes = 30; private static readonly int CheckXMinutes = 30;
public static void UpdateProcedureCheck() public static void UpdateProcedureCheck()
{ {
@ -79,7 +80,7 @@ namespace TShockAPI
private static void NotifyAdministrators(Dictionary<string, string> update) private static void NotifyAdministrators(Dictionary<string, string> update)
{ {
var changes = update["changes"].Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); var changes = update["changes"].Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries);
NotifyAdministrator(TSPlayer.Server, changes); NotifyAdministrator(TSPlayer.Server, changes);
foreach (TSPlayer player in TShock.Players) foreach (TSPlayer player in TShock.Players)
{ {

View file

@ -144,7 +144,8 @@ namespace TShockAPI
TSPlayer.Server.SendMessage(log, color); TSPlayer.Server.SendMessage(log, color);
foreach (TSPlayer player in TShock.Players) 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); player.SendMessage(log, color);
} }
} }
@ -182,14 +183,15 @@ namespace TShockAPI
string name = player.Name.ToLower(); string name = player.Name.ToLower();
if (name.Equals(ply)) if (name.Equals(ply))
return new List<TSPlayer> { player }; return new List<TSPlayer> {player};
if (name.Contains(ply)) if (name.Contains(ply))
found.Add(player); found.Add(player);
} }
return found; 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; int j = 0;
do do
@ -201,11 +203,10 @@ namespace TShockAPI
break; break;
} }
tileX = startTileX + Random.Next(tileXRange * -1, tileXRange); tileX = startTileX + Random.Next(tileXRange*-1, tileXRange);
tileY = startTileY + Random.Next(tileYRange * -1, tileYRange); tileY = startTileY + Random.Next(tileYRange*-1, tileYRange);
j++; j++;
} } while (TileValid(tileX, tileY) && !TileClear(tileX, tileY));
while (TileValid(tileX, tileY) && !TileClear(tileX, tileY));
} }
private bool TileValid(int tileX, int tileY) private bool TileValid(int tileX, int tileY)
@ -223,7 +224,7 @@ namespace TShockAPI
int type = -1; int type = -1;
if (int.TryParse(idOrName, out type)) if (int.TryParse(idOrName, out type))
{ {
return new List<Item> { GetItemById(type) }; return new List<Item> {GetItemById(type)};
} }
return GetItemByName(idOrName); return GetItemByName(idOrName);
} }
@ -243,7 +244,7 @@ namespace TShockAPI
Item item = new Item(); Item item = new Item();
item.SetDefaults(name); item.SetDefaults(name);
if (item.name == name) if (item.name == name)
return new List<Item> { item }; return new List<Item> {item};
} }
//Method #2 - allows impartial matching //Method #2 - allows impartial matching
var found = new List<Item>(); var found = new List<Item>();
@ -254,11 +255,13 @@ namespace TShockAPI
Item item = new Item(); Item item = new Item();
item.netDefaults(i); item.netDefaults(i);
if (item.name.ToLower() == name.ToLower()) if (item.name.ToLower() == name.ToLower())
return new List<Item> { item }; return new List<Item> {item};
if (item.name.ToLower().StartsWith(name.ToLower())) if (item.name.ToLower().StartsWith(name.ToLower()))
found.Add(item); found.Add(item);
} }
catch { } catch
{
}
} }
return found; return found;
} }
@ -268,7 +271,7 @@ namespace TShockAPI
int type = -1; int type = -1;
if (int.TryParse(idOrName, out type)) if (int.TryParse(idOrName, out type))
{ {
return new List<NPC> { GetNPCById(type) }; return new List<NPC> {GetNPCById(type)};
} }
return GetNPCByName(idOrName); return GetNPCByName(idOrName);
} }
@ -288,7 +291,7 @@ namespace TShockAPI
NPC npc = new NPC(); NPC npc = new NPC();
npc.SetDefaults(name); npc.SetDefaults(name);
if (npc.name == name) if (npc.name == name)
return new List<NPC> { npc }; return new List<NPC> {npc};
} }
//Method #2 - allows impartial matching //Method #2 - allows impartial matching
var found = new List<NPC>(); var found = new List<NPC>();
@ -297,7 +300,7 @@ namespace TShockAPI
NPC npc = new NPC(); NPC npc = new NPC();
npc.netDefaults(i); npc.netDefaults(i);
if (npc.name.ToLower() == name.ToLower()) if (npc.name.ToLower() == name.ToLower())
return new List<NPC> { npc }; return new List<NPC> {npc};
if (npc.name.ToLower().StartsWith(name.ToLower())) if (npc.name.ToLower().StartsWith(name.ToLower()))
found.Add(npc); found.Add(npc);
} }
@ -319,7 +322,7 @@ namespace TShockAPI
for (int i = 1; i < Main.maxBuffs; i++) for (int i = 1; i < Main.maxBuffs; i++)
{ {
if (Main.buffName[i].ToLower() == name) if (Main.buffName[i].ToLower() == name)
return new List<int> { i }; return new List<int> {i};
} }
var found = new List<int>(); var found = new List<int>();
for (int i = 1; i < Main.maxBuffs; i++) for (int i = 1; i < Main.maxBuffs; i++)
@ -334,7 +337,7 @@ namespace TShockAPI
{ {
var item = new Item(); var item = new Item();
item.SetDefaults(0); item.SetDefaults(0);
item.prefix = (byte)id; item.prefix = (byte) id;
item.AffixName(); item.AffixName();
return item.name.Trim(); return item.name.Trim();
} }
@ -347,7 +350,7 @@ namespace TShockAPI
{ {
item.prefix = (byte) i; item.prefix = (byte) i;
if (item.AffixName().Trim() == name) if (item.AffixName().Trim() == name)
return new List<int> { i }; return new List<int> {i};
} }
var found = new List<int>(); var found = new List<int>();
for (int i = 1; i < 83; i++) for (int i = 1; i < 83; i++)
@ -356,11 +359,13 @@ namespace TShockAPI
{ {
item.prefix = (byte) i; item.prefix = (byte) i;
if (item.AffixName().Trim().ToLower() == name.ToLower()) if (item.AffixName().Trim().ToLower() == name.ToLower())
return new List<int> { i }; return new List<int> {i};
if (item.AffixName().Trim().ToLower().StartsWith(name.ToLower())) if (item.AffixName().Trim().ToLower().StartsWith(name.ToLower()))
found.Add(i); found.Add(i);
} }
catch { } catch
{
}
} }
return found; return found;
} }
@ -472,15 +477,15 @@ namespace TShockAPI
{ {
string possibleColor = foo.Substring(0, 13); string possibleColor = foo.Substring(0, 13);
foo = foo.Remove(0, 13); foo = foo.Remove(0, 13);
float[] pC = { 0, 0, 0 }; float[] pC = {0, 0, 0};
possibleColor = possibleColor.Replace("%", ""); possibleColor = possibleColor.Replace("%", "");
string[] pCc = possibleColor.Split(','); string[] pCc = possibleColor.Split(',');
if (pCc.Length == 3) if (pCc.Length == 3)
{ {
try try
{ {
player.SendMessage(foo, (byte)Convert.ToInt32(pCc[0]), (byte)Convert.ToInt32(pCc[1]), player.SendMessage(foo, (byte) Convert.ToInt32(pCc[0]), (byte) Convert.ToInt32(pCc[1]),
(byte)Convert.ToInt32(pCc[2])); (byte) Convert.ToInt32(pCc[2]));
continue; continue;
} }
catch (Exception e) catch (Exception e)
@ -561,6 +566,7 @@ namespace TShockAPI
return ret.Aggregate("", (s, b) => s + b.ToString("X2")); return ret.Aggregate("", (s, b) => s + b.ToString("X2"));
} }
} }
/// <summary> /// <summary>
/// Returns a Sha256 string for a given string /// Returns a Sha256 string for a given string
/// </summary> /// </summary>