public void GroupAttributes(ISender sender, ArgumentList args) { var save = args.TryPop("-save"); var requestedGroup = args.GetString(0); var attribute = args.GetString(1); var value = args.GetString(2); if (!XmlParser.HasGroup(requestedGroup)) { throw new CommandError("{1} `{0}`", requestedGroup, Languages.NoGroup); } IPermission group = XmlParser.GetGroup(requestedGroup); SetAttribute(ref group, attribute, value); var res = XmlParser.UpdateDefiniton(group); if (save) { XmlParser.Save(); } sender.sendMessage( String.Format("{0} {1}", res ? Languages.Success : Languages.Failure, Languages.UpdatingAttribute) ); }
/// <summary> /// Sets OP status to a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void OpPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); if (Storage.IsAvailable) { var existing = Authentication.GetPlayer(playerName); if (existing != null) { if (existing.Operator) { throw new CommandError("Player is already an operator"); } if (Authentication.UpdatePlayer(playerName, null, op: true)) { Utils.NotifyAllOps("Opping " + playerName + " [" + sender.SenderName + "]", true); var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("You are now a server operator.", Color.Green); player.SetOp(true); player.SetAuthentication(player.name, "tdsm"); } sender.Message("Op success", Color.DarkGreen); } else { sender.Message("Failed to op player", Color.DarkRed); } } else { sender.Message("No user found by " + playerName, Color.DarkRed); sender.Message("Please use the `user` command", Color.DarkRed); } } else { var password = args.GetString(1); Utils.NotifyAllOps("Opping " + playerName + " [" + sender.SenderName + "]", true); Core.Ops.Add(playerName, password); var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("You are now a server operator.", Color.Green); player.SetOp(true); player.SetAuthentication(player.name, "tdsm"); } if (!Core.Ops.Save()) { Utils.NotifyAllOps("Failed to save op list [" + sender.SenderName + "]", true); return; } } }
/// <summary> /// Gives specified item to the specified player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void Give(ISender sender, ArgumentList args) { // /give <stack> <item> [prefix] [player] var index = 0; int stack = args.GetInt(index++); string name = args.GetString(index++); // var max = Tools.AvailableItemSlots; //Perhaps remove a few incase of new drops // if (stack > max) // { // stack = max; // Set to Tools.AvailableItemSlots because number given was larger than this. // } int id; var results = Int32.TryParse(name, out id) ? DefinitionManager.FindItem(id) : DefinitionManager.FindItem(name); if (results != null && results.Length > 0) { if (results.Length > 1) throw new CommandError(String.Format("More than 1 item found, total is: {0}", results.Length)); var item = results[0]; string prefix; if (args.TryGetString(index, out prefix)) { try { Affix afx; if (Enum.TryParse(prefix, out afx)) { item.Prefix = (int)afx; index++; } } catch (ArgumentException) { throw new CommandError(String.Format("Error, the Prefix you entered was not found: {0}", args.GetString(3))); } } Player receiver; if (!args.TryGetOnlinePlayer(index, out receiver)) { if (sender is Player) receiver = sender as Player; else throw new CommandError("Expected an online player"); } receiver.GiveItem(item.Id, stack, item.MaxStack, sender, item.NetId, true, item.Prefix); } else throw new CommandError(String.Format("No item known by: {0}", name)); }
public static void Warp(ISender sender, ArgumentList args) { if (sender is Player) { string warpName = args.GetString(0); Player player = sender as Player; Warp warp = WarpManager.GetWarp(warpName); if (warp == default(Warp) || !warp.IsUserAccessible(player)) { throw new CommandError("Warp not found!"); } if (warp.Location == default(Vector2)) { throw new CommandError("Warp Location is invalid!"); } if (!player.Teleport(warp.Location)) { throw new CommandError("There was an error in the Teleport."); } } }
public static void SetWarp(ISender sender, ArgumentList args) { Vector2 Location = default(Vector2); if (!(sender is Player)) { int x, y; if (!args.TryParseTwo <Int32, Int32>("", out x, "", out y)) { throw new CommandError("Non Player Senders need to provide -x & -y tile indices."); } } else { Location = (sender as Player).Position / 16; } string name = args.GetString(0); Warp warp = new Warp() { Name = name, Location = Location, Type = WarpType.PUBLIC, Users = new List <String>() }; WarpManager.WarpList.Add(warp); WarpManager.Save((args.Plugin as Essentials).WarpFile, "warp"); sender.Message("Warp {0} has been created.", warp.Name); }
public void Groups(ISender sender, ArgumentList args) { var add = args.TryPop("add"); //xgroup add groupname var save = args.TryPop("-save"); if (add) { var groupName = args.GetString(0); if (XmlParser.HasGroup(groupName)) { throw new CommandError(Languages.DefinitionsExist + Languages.Group); } XmlParser.AddGroup(groupName); if (save) { XmlParser.Save(); } sender.sendMessage( String.Format("`{0}` {1}", groupName, Languages.HasBeenCreated) ); } else { throw new CommandError(Languages.ArgumentsExpected); } }
/// <summary> /// De-OPs a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public static void DeopPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); Player player; if (args.TryGetOnlinePlayer(0, out player)) { playerName = player.Name; if (Player.isInOpList(playerName)) { player.sendMessage("You have been De-Opped!.", ChatColor.Green); } player.Op = false; if (player.HasClientMod) { NetMessage.SendData(Packet.CLIENT_MOD, player.whoAmi); } } if (Player.isInOpList(playerName)) { Server.notifyOps("De-Opping " + playerName + " {" + sender.Name + "}", true); Server.OpList.removeException(playerName + ":" + Player.GetPlayerPassword(playerName)); } if (!Server.OpList.Save()) { Server.notifyOps("OpList Failed to Save due. {" + sender.Name + "}", true); return; } }
public static void MessagePlayer(ISender sender, ArgumentList args) { var Player = args.GetOnlinePlayer(0); var Message = args.GetString(1); Player.sendMessage(String.Format("[{0}] PM: {1}", sender.Name, Message), ChatColor.DarkGray); Server.notifyOps(String.Format("PM {0} => {1}: {2}", sender.Name, Player.Name, Message)); }
/* Following few are untested */ public static void ManageWarp(ISender sender, ArgumentList args) { //remove/add players, delete warp bool delete = args.TryPop("delete"); bool remove = args.TryPop("removeplayer"); bool add = args.TryPop("addplayer"); string username = args.GetString(0); int warpIndex; if (!WarpManager.ContainsWarp(username, out warpIndex)) { throw new CommandError("No Warp by that name exists."); } if (delete) { WarpManager.WarpList.RemoveAt(warpIndex); sender.sendMessage("Warp successfully removed."); } else if (remove) { Warp warp = WarpManager.WarpList.ElementAt(warpIndex); int usrIndex; if (warp.ContainsUser(username, out usrIndex)) { warp.Users.RemoveAt(usrIndex); WarpManager.UpdateWarp(warp); sender.Message("{0} has been removed from {1}", username, warp.Name); } else { throw new CommandError("No user exists."); } } else if (add) { Warp warp = WarpManager.WarpList.ElementAt(warpIndex); int usrIndex; if (!warp.ContainsUser(username, out usrIndex)) { warp.Users.Add(WarpManager.CleanUserName(username)); WarpManager.UpdateWarp(warp); sender.Message("{0} has been added to {1}", username, warp.Name); } else { throw new CommandError("User exists already."); } } else { throw new CommandError("No Manage Action defined."); } }
/// <summary> /// De-OPs a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void DeopPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); if (Storage.IsAvailable) { var existing = Authentication.GetPlayer(playerName); if (existing != null) { if (!existing.Operator) throw new CommandError("Player is not an operator"); var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("Your server operator privledges have been revoked.", Color.DarkRed); player.SetOp(false); player.SetAuthentication(null, "tdsm"); } if (Authentication.UpdatePlayer(playerName, null, false)) { sender.Message("Deop success", Color.DarkGreen); } else { sender.Message("Failed to deop player", Color.DarkRed); } } else { sender.SendMessage("No user found by " + playerName); } } else { if (Core.Ops.Contains(playerName)) { var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("Your server operator privledges have been revoked.", Color.Green); player.SetOp(false); player.SetAuthentication(null, "tdsm"); } Utils.NotifyAllOps("De-Opping " + playerName + " [" + sender.SenderName + "]", true); Core.Ops.Remove(playerName, true); if (!Core.Ops.Save()) { Utils.NotifyAllOps("Failed to save op list [" + sender.SenderName + "]", true); } } else sender.SendMessage("No user found by " + playerName); } }
public void GroupAttributes(ISender sender, ArgumentList args) { var save = args.TryPop("-save"); var requestedGroup = args.GetString(0); var attribute = args.GetString(1); var value = args.GetString(2); if (!XmlParser.HasGroup(requestedGroup)) throw new CommandError("{1} `{0}`", requestedGroup, Languages.NoGroup); IPermission group = XmlParser.GetGroup(requestedGroup); SetAttribute(ref group, attribute, value); var res = XmlParser.UpdateDefiniton(group); if (save) XmlParser.Save(); sender.sendMessage( String.Format("{0} {1}", res ? Languages.Success : Languages.Failure, Languages.UpdatingAttribute) ); }
void Debug(ISender sender, ArgumentList args) { var cmd = args.GetString(0); switch (cmd) { case "programlog.debug": ProgramLog.Debug.EnableConsoleOutput = !ProgramLog.Debug.EnableConsoleOutput; sender.Message("ProgramLog.Debug.EnableConsoleOutput: " + ProgramLog.Debug.EnableConsoleOutput); break; default: throw new CommandError("Invalid sub command " + cmd); } }
public void UserAttributes(ISender sender, ArgumentList args) { var save = args.TryPop("-save"); var requestedUser = args.GetString(0); var attribute = args.GetString(1); var value = args.GetString(2); Player trueUser = null; var matches = Server.FindPlayerByPart(requestedUser); if (matches.Count == 1) { trueUser = matches.ToArray()[0]; } var username = trueUser == null ? requestedUser : (trueUser.Name ?? requestedUser); if (!XmlParser.HasUser(username)) { throw new CommandError("{1} `{0}`", username, Languages.NoUser); } IPermission user = XmlParser.GetUser(username); SetAttribute(ref user, attribute, value); var res = XmlParser.UpdateDefiniton(user); if (save) { XmlParser.Save(); } sender.sendMessage( String.Format("{0} {1}", res ? Languages.Success : Languages.Failure, Languages.UpdatingAttribute) ); }
public void Users(ISender sender, ArgumentList args) { var add = args.TryPop("add"); //xuser add username var forced = args.TryPop("-f"); var save = args.TryPop("-save"); if (add) { var username = args.GetString(0); Player user = null; var matches = Server.FindPlayerByPart(username); if (matches.Count == 1) { user = matches.ToArray()[0]; } if (user == null && !forced) { throw new CommandError(Languages.NoPlayersAndForce); } var trueUser = user == null ? username : (user.Name ?? username); if (XmlParser.HasUser(trueUser)) { throw new CommandError(Languages.DefinitionsExist + Languages.User); } XmlParser.AddUser(trueUser); if (save) { XmlParser.Save(); } sender.sendMessage( String.Format("`{0}` {1}", trueUser, Languages.HasBeenCreated) ); } else { throw new CommandError("{0} - xuser add [-f -save] username", Languages.ArgumentsExpected); } }
/// <summary> /// Sets OP status to a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public static void OpPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); var password = args.GetString(1); Player player; if (args.TryGetOnlinePlayer(0, out player)) { playerName = player.Name; player.sendMessage("You are now OP!", ChatColor.Green); player.Op = true; if (player.HasClientMod) { NetMessage.SendData(Packet.CLIENT_MOD, player.whoAmi); } } Server.notifyOps("Opping " + playerName + " {" + sender.Name + "}", true); Server.OpList.addException(playerName + ":" + password, true, playerName.Length + 1); if (!Server.OpList.Save()) { Server.notifyOps("OpList Failed to Save due. {" + sender.Name + "}", true); return; } }
internal static void RConCommand(ISender sender, ArgumentList args) { string name; if (args.TryParseOne ("cut", out name)) { if (sender is Player || sender is RConSender) { sender.sendMessage ("You cannot perform that action.", 255, 238, 130, 238); return; } var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) rcon.Close (); } ProgramLog.Admin.Log ("Cut all remote console connections from {0}.", name); } else if (args.TryParseOne ("ban", out name)) { if (sender is Player || sender is RConSender) { sender.sendMessage ("You cannot perform that action.", 255, 238, 130, 238); return; } LoginDatabase.setValue (name, null); var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) rcon.Close (); } ProgramLog.Admin.Log ("Cut all remote console connections from {0} and revoked credentials.", name); } else if (args.Count == 1 && args.GetString(0) == "list") { foreach (var rcon in clients) { sender.sendMessage (String.Format ("{0} {1}", rcon.Id, rcon.state)); } } else if (args.Count == 1 && args.GetString(0) == "load") { if (sender is Player || sender is RConSender) { sender.sendMessage ("You cannot perform that action.", 255, 238, 130, 238); return; } LoginDatabase.Load (); ProgramLog.Admin.Log ("Reloaded remote console login database."); } else { throw new CommandError (""); } }
/// <summary> /// Allows an OP to force the time to dtay at a certain point. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public static void Timelock(ISender sender, ArgumentList args) { var disable = args.TryPop("disable"); var setNow = args.TryPop("now"); var setMode = args.TryPop("set"); var setAt = args.TryPop("setat"); if (disable) { if (!Main.UseTimeLock) { sender.sendMessage("Time lock is already disabled", 255, 255, 0, 0); return; } Main.UseTimeLock = false; sender.sendMessage("Time lock has been disabled.", 255, 0, 255, 0); return; } else if (setNow) Main.UseTimeLock = true; else if (setMode) { string caseType = args.GetString(0); switch (caseType) { case "day": { World.SetTime(13500.0); break; } case "dawn": { World.SetTime(0); break; } case "dusk": { World.SetTime(0, false, false); break; } case "noon": { World.SetTime(27000.0); break; } case "night": { World.SetTime(16200.0, false, false); break; } default: { sender.sendMessage(Languages.PleaseReview, 255, 255, 0, 0); return; } } Main.UseTimeLock = true; } else if (setAt) { double time; if (args.TryParseOne<Double>(out time)) { Main.Time = time; Main.UseTimeLock = true; } else throw new CommandError("Double expected."); } else throw new CommandError("Certain arguments expected."); if (Main.UseTimeLock) { if (!setNow) NetMessage.SendData(Packet.WORLD_DATA); sender.sendMessage( String.Format("Time lock has set at {0}.", Main.Time), 255, 0, 255, 0 ); } }
public void RepositoryCommand(ISender sender, ArgumentList args) { var cmd = args.GetString(0); string pkg; bool all; switch (cmd) { /*case "search": Lets see how many plugins we have break;*/ //#if DEBUG // case "check": //Maybe b3 // //Purpose is to check if all plugins are supported by the latest heartbeat TDSM version // //Gather plugin names + version and send to heartbeat in one request // //Heartbeat responds json messages direct to console: // // [ // // { // // Colour: {}, // // Message: "TDSM Core [READY]" // // }, // // { // // Colour: {}, // // Message: "Restrict [No update]" // // } // // ] // sender.Message("Not yet implemented"); // break; //#endif case "status": pkg = args.GetString(1); all = pkg == "-all"; sender.Message("Finding updates...", Microsoft.Xna.Framework.Color.Yellow); var packages = Repository.GetAvailableUpdate(all ? null : pkg); if (packages != null && packages.Length > 0) { sender.Message("Found update{0}:", Microsoft.Xna.Framework.Color.Yellow, packages.Length > 1 ? "s" : String.Empty); foreach (var upd in packages) { var vers = String.Empty; if (!String.IsNullOrEmpty(upd.Version)) vers = " [" + upd.Version + "]"; var desc = String.Empty; if (!String.IsNullOrEmpty(upd.ShortDescription)) desc = " - " + upd.ShortDescription; sender.Message(upd.Name + vers + desc, Microsoft.Xna.Framework.Color.Green); } } else { sender.Message(all ? "No updates available" : ("No package called: " + pkg), Microsoft.Xna.Framework.Color.Red); } break; case "update": pkg = args.GetString(1); all = pkg == "-all"; sender.Message("Finding updates...", Microsoft.Xna.Framework.Color.Yellow); try { var updates = Repository.GetAvailableUpdate(all ? null : pkg); if (updates != null && updates.Length > 0) { if (!all && updates.Length > 1) { sender.Message("Too many packages found, please inform the TDSM Team", Microsoft.Xna.Framework.Color.Red); return; } sender.Message("Found {0} update{1}:", Microsoft.Xna.Framework.Color.Yellow, updates.Length, updates.Length > 1 ? "s" : String.Empty); foreach (var upd in updates) { sender.Message("Updating {0}", Microsoft.Xna.Framework.Color.Green, upd.Name); try { if (Repository.PerformUpdate(upd)) { sender.Message("Install complete", Microsoft.Xna.Framework.Color.Green); } else { sender.Message("Install failed", Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } } } else { sender.Message(all ? "No updates available" : ("No update or package for: " + pkg), Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } break; case "install": pkg = args.GetString(1); sender.Message("Finding package...", Microsoft.Xna.Framework.Color.Yellow); try { var install = Repository.GetAvailableUpdate(pkg, false); if (install != null && install.Length > 0) { if (install.Length > 1) { sender.Message("Too many packages found, please inform the TDSM Team", Microsoft.Xna.Framework.Color.Red); return; } //Ensure not already installed foreach (var plg in PluginManager.EnumeratePlugins) { if (plg.Name.ToLower() == pkg) { sender.Message("Package already installed, please use 'repo update \"" + pkg + "\"'", Microsoft.Xna.Framework.Color.Red); break; } } foreach (var upd in install) { sender.Message("Installing {0}", Microsoft.Xna.Framework.Color.Green, upd.Name); try { if (Repository.PerformUpdate(upd)) { sender.Message("Install complete", Microsoft.Xna.Framework.Color.Green); } else { sender.Message("Install failed", Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } } } else { sender.Message("No package called: " + pkg, Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } break; default: throw new CommandError("No such command: " + cmd); } }
public void Invasion(ISender sender, ArgumentList args) { if (Main.invasionType == 0) { var custom = args.TryPop("-custom"); if (custom) { if (args.Count > 0) { var npcIds = new List<Int32>(); while (args.Count > 0) { int npcType; string npc; if (args.TryGetInt(0, out npcType)) { npcIds.Add(npcType); } else if (args.TryGetString(0, out npc)) { var match = Definitions.DefinitionManager.FindNPC(npc); if (match.Length == 1) { npcIds.Add(match[0].Id); } else if (match.Length == 0) { sender.Message("Cannot find a NPC by `{0}`", npc); return; } else { sender.Message("Found too many NPC's containing `{0}`", npc); return; } } else { throw new CommandError("Expected a NPC id or name."); } } //Schedule... //if (!_customInvasion.IsEmpty()) _customInvasion.Enabled = false; //_customInvasion = new Task() //{ // Trigger = 10, // Data = npcIds, // Method = (task) => // { // var ids = task.Data as List<Int32>; // for (var x = 0; x < 5; x++) // { // var ix = Main.rand.Next(0, ids.Count - 1); // var pos = FindPositionOutOfSight(); // if (pos.HasValue) // { // } // } // } //}; if (_invasion != null) lock (_invasion) _invasion = npcIds; else _invasion = npcIds; Main.StartInvasion(_assignedInvasionType); } else throw new CommandError("Expected npc type or name"); } else { var txt = args.GetString(0).ToLower(); var vals = Enum.GetValues(typeof(InvasionType)); foreach (InvasionType it in vals) { if (it.ToString().ToLower() == txt) { Main.StartInvasion((int)it); sender.Message("A {0} invasion has begun.", it); return; } } sender.Message("No such invasion of type {0}", txt); } } else { if (args.TryPop("end") || args.TryPop("stop") || args.TryPop("cancel")) { //if (!_customInvasion.IsEmpty()) _customInvasion.Enabled = false; Main.invasionType = 0; if (_invasion != null) lock (_invasion) _invasion.Clear(); sender.Message("The invasion has now been stopped."); } else sender.Message("An invasion is already under way."); } }
void ManageApi(ISender sender, ArgumentList args) { if (!Storage.IsAvailable) { throw new CommandError("No permissions plugin or data plugin is attached"); } var a = 0; string name, pass, type, value; APIAccount acc = null; var cmd = args.GetString(a++); switch (cmd) { case "addaccount": //api addaccount "username" "password" if (!args.TryGetString(a++, out name)) { throw new CommandError("Expected username after [" + cmd + "]"); } if (!args.TryGetString(a++, out pass)) { throw new CommandError("Expected password after username"); } acc = APIAccountManager.FindByName(name); if (acc == null) { acc = APIAccountManager.Create(name, pass); if (acc.Id > 0) { sender.SendMessage("Successfully created account.", R: 0, B: 0); } else { sender.SendMessage("Failed to create account.", G: 0, B: 0); } } else { throw new CommandError("Existing API account found by " + name); } break; case "removeaccount": //api removeaccount "username" if (!args.TryGetString(a++, out name)) { throw new CommandError("Expected username after [" + cmd + "]"); } acc = APIAccountManager.FindByName(name); if (acc != null) { if (APIAccountManager.DeleteAccount(acc.Id)) { sender.SendMessage("Successfully removed account.", R: 0, B: 0); } else { sender.SendMessage("Failed to remove account.", G: 0, B: 0); } } else { throw new CommandError("No API account found by " + name); } break; case "addrole": //api addrole "account" "type" "value" if (!args.TryGetString(a++, out name)) { throw new CommandError("Expected username after [" + cmd + "]"); } if (!args.TryGetString(a++, out type)) { throw new CommandError("Expected type after username"); } if (!args.TryGetString(a++, out value)) { throw new CommandError("Expected value after type"); } acc = APIAccountManager.FindByName(name); if (acc != null) { var role = APIAccountManager.AddType(acc.Id, type, value); if (role != null && role.Id > 0) { sender.SendMessage("Successfully added role account.", R: 0, B: 0); } else { sender.SendMessage("Failed to add role to account.", G: 0, B: 0); } } else { throw new CommandError("No API account found by " + name); } break; case "removerole": //api removerole "account" "type" "value" if (!args.TryGetString(a++, out name)) { throw new CommandError("Expected username after [" + cmd + "]"); } if (!args.TryGetString(a++, out type)) { throw new CommandError("Expected type after username"); } if (!args.TryGetString(a++, out value)) { throw new CommandError("Expected value after type"); } acc = APIAccountManager.FindByName(name); if (acc != null) { var role = APIAccountManager.DeleteType(acc.Id, type, value); if (role) { sender.SendMessage("Successfully removed role account.", R: 0, B: 0); } else { sender.SendMessage("Failed to removed role from account.", G: 0, B: 0); } } else { throw new CommandError("No API account found by " + name); } break; case "search": //api search "part" if (!args.TryGetString(a++, out name)) { throw new CommandError("Expected part of a acount name after [" + cmd + "]"); } var matches = APIAccountManager.FindAccountsByPrefix(name); if (matches != null && matches.Length > 0) { sender.Message("Matches:"); foreach (var mth in matches) { sender.Message("\t" + mth); } } else { sender.Message("There are no registered accounts matching " + name); } break; default: throw new CommandError("Invalid command " + cmd); } }
public void RepositoryCommand(ISender sender, ArgumentList args) { var cmd = args.GetString(0); string pkg; bool all; switch (cmd) { /*case "search": Lets see how many plugins we have * break;*/ //#if DEBUG // case "check": //Maybe b3 // //Purpose is to check if all plugins are supported by the latest heartbeat TDSM version // //Gather plugin names + version and send to heartbeat in one request // //Heartbeat responds json messages direct to console: // // [ // // { // // Colour: {}, // // Message: "TDSM Core [READY]" // // }, // // { // // Colour: {}, // // Message: "Restrict [No update]" // // } // // ] // sender.Message("Not yet implemented"); // break; //#endif case "status": pkg = args.GetString(1); all = pkg == "-all"; sender.Message("Finding updates...", Microsoft.Xna.Framework.Color.Yellow); var packages = Repository.GetAvailableUpdate(all ? null : pkg); if (packages != null && packages.Length > 0) { sender.Message("Found update{0}:", Microsoft.Xna.Framework.Color.Yellow, packages.Length > 1 ? "s" : String.Empty); foreach (var upd in packages) { var vers = String.Empty; if (!String.IsNullOrEmpty(upd.Version)) { vers = " [" + upd.Version + "]"; } var desc = String.Empty; if (!String.IsNullOrEmpty(upd.ShortDescription)) { desc = " - " + upd.ShortDescription; } sender.Message(upd.Name + vers + desc, Microsoft.Xna.Framework.Color.Green); } } else { sender.Message(all ? "No updates available" : ("No package called: " + pkg), Microsoft.Xna.Framework.Color.Red); } break; case "update": pkg = args.GetString(1); all = pkg == "-all"; sender.Message("Finding updates...", Microsoft.Xna.Framework.Color.Yellow); try { var updates = Repository.GetAvailableUpdate(all ? null : pkg); if (updates != null && updates.Length > 0) { if (!all && updates.Length > 1) { sender.Message("Too many packages found, please inform the TDSM Team", Microsoft.Xna.Framework.Color.Red); return; } sender.Message("Found {0} update{1}:", Microsoft.Xna.Framework.Color.Yellow, updates.Length, updates.Length > 1 ? "s" : String.Empty); foreach (var upd in updates) { sender.Message("Updating {0}", Microsoft.Xna.Framework.Color.Green, upd.Name); try { if (Repository.PerformUpdate(upd)) { sender.Message("Install complete", Microsoft.Xna.Framework.Color.Green); } else { sender.Message("Install failed", Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } } } else { sender.Message(all ? "No updates available" : ("No update or package for: " + pkg), Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } break; case "install": pkg = args.GetString(1); sender.Message("Finding package...", Microsoft.Xna.Framework.Color.Yellow); try { var install = Repository.GetAvailableUpdate(pkg, false); if (install != null && install.Length > 0) { if (install.Length > 1) { sender.Message("Too many packages found, please inform the TDSM Team", Microsoft.Xna.Framework.Color.Red); return; } //Ensure not already installed foreach (var plg in PluginManager.EnumeratePlugins) { if (plg.Name.ToLower() == pkg) { sender.Message("Package already installed, please use 'repo update \"" + pkg + "\"'", Microsoft.Xna.Framework.Color.Red); break; } } foreach (var upd in install) { sender.Message("Installing {0}", Microsoft.Xna.Framework.Color.Green, upd.Name); try { if (Repository.PerformUpdate(upd)) { sender.Message("Install complete", Microsoft.Xna.Framework.Color.Green); } else { sender.Message("Install failed", Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } } } else { sender.Message("No package called: " + pkg, Microsoft.Xna.Framework.Color.Red); } } catch (RepositoryError err) { sender.Message(err.Message, Microsoft.Xna.Framework.Color.Red); } break; default: throw new CommandError("No such command: " + cmd); } }
/// <summary> /// Allows an OP to force the time to dtay at a certain point. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public void Timelock(ISender sender, ArgumentList args) { var disable = args.TryPop("disable"); var setNow = args.TryPop("now"); var setMode = args.TryPop("set"); var setAt = args.TryPop("setat"); if (disable) { if (!(args.Plugin as Entry).UseTimeLock) { sender.Message("Time lock is already disabled", 255, 255, 0, 0); return; } (args.Plugin as Entry).UseTimeLock = false; sender.Message("Time lock has been disabled.", 255, 0, 255, 0); return; } else if (setNow) { (args.Plugin as Entry).UseTimeLock = true; } else if (setMode) { string caseType = args.GetString(0); switch (caseType) { case "day": { World.SetTime(13500.0); break; } case "dawn": { World.SetTime(0); break; } case "dusk": { World.SetTime(0, false); break; } case "noon": { World.SetTime(27000.0); break; } case "night": { World.SetTime(16200.0, false); break; } default: { sender.Message("Please review your command.", 255, 255, 0, 0); return; } } (args.Plugin as Entry).UseTimeLock = true; } else if (setAt) { double time; if (args.TryParseOne <Double>(out time)) { Core.TimelockTime = time; Core.TimelockRain = Main.raining; Core.TimelockSlimeRain = Main.slimeRain; Core.UseTimeLock = true; } else { throw new CommandError("Double expected."); } } else { throw new CommandError("Certain arguments expected."); } if ((args.Plugin as Entry).UseTimeLock) { if (!setNow) { NetMessage.SendData((int)Packet.WORLD_DATA); } sender.Message( String.Format("Time lock has set at {0}.", (args.Plugin as Entry).TimelockTime), 255, 0, 255, 0 ); } }
void WhitelistMan(ISender sender, ArgumentList args) { var index = 0; var cmd = args.GetString(index++); string name, ip; switch (cmd) { case "status": case "current": case "?": sender.Message("The whitelist is currently " + (Core.Config.WhitelistEnabled ? "enabled" : "disabled")); break; case "reload": Core.Whitelist.Load(); Utils.NotifyAllOps("The whitelist was reloaded"); break; case "enable": if (!Core.Config.WhitelistEnabled) { Core.Config.WhitelistEnabled = true; if (!ConfigUpdater.IsAvailable || ConfigUpdater.Set("whitelist", Core.Config.WhitelistEnabled)) { Utils.NotifyAllOps("The whitelist was enabled"); } else sender.Message("Failed to save to config, whitelist is only enabled this session.", Color.Red); } else sender.Message("The whitelist is already enabled", Color.Red); break; case "disable": if (Core.Config.WhitelistEnabled) { Core.Config.WhitelistEnabled = false; if (!ConfigUpdater.IsAvailable || ConfigUpdater.Set("whitelist", Core.Config.WhitelistEnabled)) { Utils.NotifyAllOps("The whitelist was disabled"); } else sender.Message("Failed to save to config, whitelist is only disabled this session.", Color.Red); } else sender.Message("The whitelist is already disabled", Color.Red); break; case "addplayer": if (!args.TryGetString(index++, out name)) { throw new CommandError("Expected player name after [addplayer]"); } var addName = Prefix_WhitelistName + name; if (Core.Whitelist.Add(addName)) { Utils.NotifyAllOps(String.Format("Player {0} was added to the whitelist", name)); if (!Core.Config.WhitelistEnabled) sender.Message("Note, the whitelist is not enabled", Color.Orange); } else sender.Message("Failed to add " + name + " to the whitelist", Color.Red); break; case "removeplayer": if (!args.TryGetString(index++, out name)) { throw new CommandError("Expected player name after [removeplayer]"); } var removeName = Prefix_WhitelistName + name; if (Core.Whitelist.Remove(removeName)) { Utils.NotifyAllOps(String.Format("Player {0} was removed from the whitelist", name)); if (!Core.Config.WhitelistEnabled) sender.Message("Note, the whitelist is not enabled", Color.Orange); } else sender.Message("Failed to remove " + name + " from the whitelist", Color.Red); break; case "addip": if (!args.TryGetString(index++, out ip)) { throw new CommandError("Expected IP after [addip]"); } var addIP = Prefix_WhitelistIp + ip; if (Core.Whitelist.Add(addIP)) { Utils.NotifyAllOps(String.Format("IP {0} was added to the whitelist", ip)); if (!Core.Config.WhitelistEnabled) sender.Message("Note, the whitelist is not enabled", Color.Orange); } else sender.Message("Failed to add " + ip + " to the whitelist", Color.Red); break; case "removeip": if (!args.TryGetString(index++, out ip)) { throw new CommandError("Expected IP after [removeip]"); } var removeIP = Prefix_WhitelistIp + ip; if (Core.Whitelist.Remove(removeIP)) { Utils.NotifyAllOps(String.Format("IP {0} was removed from the whitelist", ip)); if (!Core.Config.WhitelistEnabled) sender.Message("Note, the whitelist is not enabled", Color.Orange); } else sender.Message("Failed to remove " + ip + " from the whitelist", Color.Red); break; default: throw new CommandError("Unknown whitelist command: " + cmd); } }
void WhitelistMan(ISender sender, ArgumentList args) { var index = 0; var cmd = args.GetString(index++); string name, ip; switch (cmd) { case "status": case "current": case "?": sender.Message("The whitelist is currently " + (Core.Config.WhitelistEnabled ? "enabled" : "disabled")); break; case "reload": Core.Whitelist.Load(); Utils.NotifyAllOps("The whitelist was reloaded"); break; case "enable": if (!Core.Config.WhitelistEnabled) { Core.Config.WhitelistEnabled = true; if (!ConfigUpdater.IsAvailable || ConfigUpdater.Set("whitelist", Core.Config.WhitelistEnabled)) { Utils.NotifyAllOps("The whitelist was enabled"); } else { sender.Message("Failed to save to config, whitelist is only enabled this session.", Color.Red); } } else { sender.Message("The whitelist is already enabled", Color.Red); } break; case "disable": if (Core.Config.WhitelistEnabled) { Core.Config.WhitelistEnabled = false; if (!ConfigUpdater.IsAvailable || ConfigUpdater.Set("whitelist", Core.Config.WhitelistEnabled)) { Utils.NotifyAllOps("The whitelist was disabled"); } else { sender.Message("Failed to save to config, whitelist is only disabled this session.", Color.Red); } } else { sender.Message("The whitelist is already disabled", Color.Red); } break; case "addplayer": if (!args.TryGetString(index++, out name)) { throw new CommandError("Expected player name after [addplayer]"); } var addName = Prefix_WhitelistName + name; if (Core.Whitelist.Add(addName)) { Utils.NotifyAllOps(String.Format("Player {0} was added to the whitelist", name)); if (!Core.Config.WhitelistEnabled) { sender.Message("Note, the whitelist is not enabled", Color.Orange); } } else { sender.Message("Failed to add " + name + " to the whitelist", Color.Red); } break; case "removeplayer": if (!args.TryGetString(index++, out name)) { throw new CommandError("Expected player name after [removeplayer]"); } var removeName = Prefix_WhitelistName + name; if (Core.Whitelist.Remove(removeName)) { Utils.NotifyAllOps(String.Format("Player {0} was removed from the whitelist", name)); if (!Core.Config.WhitelistEnabled) { sender.Message("Note, the whitelist is not enabled", Color.Orange); } } else { sender.Message("Failed to remove " + name + " from the whitelist", Color.Red); } break; case "addip": if (!args.TryGetString(index++, out ip)) { throw new CommandError("Expected IP after [addip]"); } var addIP = Prefix_WhitelistIp + ip; if (Core.Whitelist.Add(addIP)) { Utils.NotifyAllOps(String.Format("IP {0} was added to the whitelist", ip)); if (!Core.Config.WhitelistEnabled) { sender.Message("Note, the whitelist is not enabled", Color.Orange); } } else { sender.Message("Failed to add " + ip + " to the whitelist", Color.Red); } break; case "removeip": if (!args.TryGetString(index++, out ip)) { throw new CommandError("Expected IP after [removeip]"); } var removeIP = Prefix_WhitelistIp + ip; if (Core.Whitelist.Remove(removeIP)) { Utils.NotifyAllOps(String.Format("IP {0} was removed from the whitelist", ip)); if (!Core.Config.WhitelistEnabled) { sender.Message("Note, the whitelist is not enabled", Color.Orange); } } else { sender.Message("Failed to remove " + ip + " from the whitelist", Color.Red); } break; default: throw new CommandError("Unknown whitelist command: " + cmd); } }
void UserPermission(ISender sender, ArgumentList args) { if (!Storage.IsAvailable) { throw new CommandError("No permissions plugin or data plugin is attached"); } int a = 0; string username, groupName, node, password; DbPlayer user; Group grp; bool deny, op; var cmd = args.GetString(a++); switch (cmd) { case "addgroup": //user addgroup "username" "group" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after username"); } user = Authentication.GetPlayer(username); if (null == user) { throw new CommandError("No user found by: " + username); } grp = Storage.FindGroup(groupName); if (grp == null) { throw new CommandError("Group does not exist: " + groupName); } if (Storage.AddUserToGroup(user.Name, grp.Name)) { sender.Message(String.Format("Successfully added {0} to group {1} ", user.Name, grp.Name), Color.Green); } else { sender.Message(String.Format("Failed to add {0} from group {1} ", user.Name, grp.Name), Color.Red); } break; case "removegroup": //user removegroup "username" "group" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after username"); } user = Authentication.GetPlayer(username); if (null == user) { throw new CommandError("No user found by: " + username); } grp = Storage.FindGroup(groupName); if (grp == null) { throw new CommandError("Group does not exist: " + groupName); } if (Storage.RemoveUserFromGroup(user.Name, grp.Name)) { sender.Message(String.Format("Successfully removed {0} to group {1} ", user.Name, grp.Name), Color.Green); } else { sender.Message(String.Format("Failed to remove {0} from group {1} ", user.Name, grp.Name), Color.Red); } break; case "addnode": //user addnode "username" "node" "deny" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } if (!args.TryGetString(a++, out node)) { throw new CommandError("Expected node name after username"); } if (!args.TryGetBool(a++, out deny)) { deny = false; } user = Authentication.GetPlayer(username); if (null == user) { throw new CommandError("No user found by: " + username); } if (Storage.AddNodeToUser(user.Name, node, deny ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully added {0} to user {1} ", node, user.Name), Color.Green); } else { sender.Message(String.Format("Failed to add {0} from user {1} ", node, user.Name), Color.Red); } break; case "removenode": //user removenode "username" "node" "deny" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } if (!args.TryGetString(a++, out node)) { throw new CommandError("Expected node name after username"); } if (!args.TryGetBool(a++, out deny)) { deny = false; } user = Authentication.GetPlayer(username); if (null == user) { throw new CommandError("No user found by: " + username); } if (Storage.RemoveNodeFromUser(user.Name, node, deny ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully removed {0} to user {1} ", node, user.Name), Color.Green); } else { sender.Message(String.Format("Failed to remove {0} from user {1} ", node, user.Name), Color.Red); } break; case "groups": case "listgroups": if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } user = Authentication.GetPlayer(username); if (null == user) { throw new CommandError("No user found by: " + username); } var groups = Storage.UserGroupList(username); if (groups != null && groups.Length > 0) { sender.Message("Current groups:"); foreach (var gps in groups) { sender.Message("\t" + gps); } } else { sender.Message("There are no registered groups for user " + user.Name); } break; case "nodes": case "listnodes": if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } user = Authentication.GetPlayer(username); if (null == user) { throw new CommandError("No user found by: " + username); } var nodes = Storage.UserNodes(username); if (nodes != null && nodes.Length > 0) { sender.Message("Current permissions for user {0}:", user.Name); foreach (var nd in nodes) { sender.Message("\t{0}\t- {1}", (nd.Permission == Permission.Denied) ? "Denied" : "Allowed", nd.Node); } } else { sender.Message("There are no permissions assigned to user: "******"search": //user search "part" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected part of a users name after [" + cmd + "]"); } var matches = Authentication.FindPlayersByPrefix(username, true); if (matches != null && matches.Length > 0) { sender.Message("Matches:"); foreach (var mth in matches) { sender.Message("\t" + mth); } } else { sender.Message("There are no registered users matching " + username); } break; case "add": //user add "username" "password" [-op | groupname] if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } if (!args.TryGetString(a++, out password)) { throw new CommandError("Expected password name after username"); } grp = null; groupName = String.Empty; if (!args.TryGetBool(a, out op)) { if (!args.TryGetString(a++, out groupName)) { groupName = String.Empty; } } else { a++; } op = groupName.ToLower() == "-op" || groupName.ToLower() == "op"; if (!op && args.Count == 4) { grp = Storage.FindGroup(groupName); if (grp == null || grp.Id == 0) { sender.Message("No group found by {0}", groupName); } } var existing = Authentication.GetPlayer(username); if (existing == null) { if (Authentication.CreatePlayer(username, password, op) != null) { if (op) { sender.Message("Successfully created user as operator: " + username); } else { if (args.Count == 4) { if (grp != null) { if (Storage.AddUserToGroup(username, grp.Name)) { sender.Message("Successfully created user {0} as a member of group {1}", Color.Green, username, grp.Name); } else { sender.Message("Successfully created user {0}, but failed associate group {1}", Color.Green, username, grp.Name); } } } else { sender.Message("Successfully created user " + username, Color.Green); } } } else { throw new CommandError("User failed to be created"); } } else { throw new CommandError("A user already exists by the name " + username); } break; case "update": //user update "username" "password" "op" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } if (!args.TryGetString(a++, out password)) { throw new CommandError("Expected password name after username"); } args.TryGetBool(a++, out op); var updatee = Authentication.GetPlayer(username); if (updatee != null) { if (Authentication.UpdatePlayer(username, password, op)) { if (op) { sender.Message("Successfully updated user as operator: " + username); } else { sender.Message("Successfully updated user " + username); } } else { throw new CommandError("User failed to be updated"); } } else { throw new CommandError("No user exists by the name " + username); } break; case "remove": //user remove "username" if (!args.TryGetString(a++, out username)) { throw new CommandError("Expected username name after [" + cmd + "]"); } var delUser = Authentication.GetPlayer(username); if (delUser != null) { if (Authentication.DeletePlayer(username)) { sender.Message("Successfully removed user " + username); } else { throw new CommandError("User failed to be removed"); } } else { throw new CommandError("Cannot find user " + username); } break; default: throw new CommandError("Invalid command " + cmd); } }
void GroupPermission(ISender sender, ArgumentList args) { if (!Storage.IsAvailable) { throw new CommandError("No permissions plugin or data plugin is attached"); } int a = 0; string groupName; bool applyToGuests; string parent, prefix, suffix; byte r = 0, g = 0, b = 0; var cmd = args.GetString(a++); switch (cmd) { case "add": //group add "Guest" <ApplyToGuests> <Parent> <R> <G> <B> <Prefix> <Suffix> if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after [" + cmd + "]"); } args.TryGetBool(a++, out applyToGuests); args.TryGetString(a++, out parent); if (!args.TryGetByte(a++, out r)) { r = 255; } if (!args.TryGetByte(a++, out g)) { g = 255; } if (!args.TryGetByte(a++, out b)) { b = 255; } args.TryGetString(a++, out prefix); args.TryGetString(a++, out suffix); if (Storage.FindGroup(groupName) != null) { throw new CommandError("There is already a group defined as " + groupName); } if (Storage.AddOrUpdateGroup(groupName, applyToGuests, parent, r, g, b, prefix, suffix) != null) { sender.Message("Successfully created group " + groupName, Color.Green); } else { sender.Message("Failed to create group " + groupName, Color.Red); } break; case "remove": //group remove "Guest if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after [" + cmd + "]"); } if (Storage.FindGroup(groupName) == null) { throw new CommandError("Group does not exist: " + groupName); } if (Storage.RemoveGroup(groupName)) { sender.Message("Successfully removed group " + groupName, Color.Green); } else { sender.Message("Failed to remove group " + groupName, Color.Red); } break; case "update": //group update "Guest" <ApplyToGuests> <Parent> <R> <G> <B> <Prefix> <Suffix> if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after [" + cmd + "]"); } args.TryGetBool(a++, out applyToGuests); args.TryGetString(a++, out parent); if (!args.TryGetByte(a++, out r)) { r = 255; } if (!args.TryGetByte(a++, out g)) { g = 255; } if (!args.TryGetByte(a++, out b)) { b = 255; } args.TryGetString(a++, out prefix); args.TryGetString(a++, out suffix); if (Storage.FindGroup(groupName) == null) { throw new CommandError("This is no group defined as " + groupName); } if (Storage.AddOrUpdateGroup(groupName, applyToGuests, parent, r, g, b, prefix, suffix) != null) { sender.Message("Successfully updated group " + groupName, Color.Green); } else { sender.Message("Failed to update group " + groupName, Color.Red); } break; case "addnode": //group addnode "Guest" "tdsm.help" <deny> if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after [" + cmd + "]"); } string addNode; if (!args.TryGetString(a++, out addNode)) { throw new CommandError("Expected node name after group name"); } bool deny; if (!args.TryGetBool(a++, out deny)) { deny = false; } if (Storage.FindGroup(groupName) == null) { throw new CommandError("Group does not exist: " + groupName); } if (Storage.AddGroupNode(groupName, addNode, deny ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully added node {0} to group {1} ", addNode, groupName), Color.Green); } else { sender.Message(String.Format("Failed to add node {0} to group {1} ", addNode, groupName), Color.Red); } break; case "removenode": //group removenode "Guest" "tdsm.help" if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after [" + cmd + "]"); } string remNode; if (!args.TryGetString(a++, out remNode)) { throw new CommandError("Expected node name after group name"); } if (Storage.FindGroup(groupName) == null) { throw new CommandError("Group does not exist: " + groupName); } bool denied; if (!args.TryGetBool(a++, out denied)) { denied = false; } if (Storage.RemoveGroupNode(groupName, remNode, denied ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully removed node {0} from group {1} ", remNode, groupName), Color.Green); } else { sender.Message(String.Format("Failed to remove node {0} from group {1} ", remNode, groupName), Color.Red); } break; case "list": //group list var groups = Storage.GroupList(); if (groups != null && groups.Length > 0) { sender.Message("Current groups:"); foreach (var grp in groups) { sender.Message("\t" + grp); } } else { sender.Message("There are no registered groups."); } break; case "listnodes": //group listnodes "Guest" //Could be used in 'list' but this will make things a bit more simple for the end user. if (!args.TryGetString(a++, out groupName)) { throw new CommandError("Expected group name after [" + cmd + "]"); } var grpList = Storage.FindGroup(groupName); if (grpList == null) { throw new CommandError("Group does not exist: " + groupName); } var nodes = Storage.GroupNodes(groupName); if (nodes != null && nodes.Length > 0) { sender.Message("Current permissions for group {0}:", grpList.Name); foreach (var nd in nodes) { sender.Message("\t{0}\t- {1}", (nd.Permission == Permission.Denied) ? "Denied" : "Allowed", nd.Node); } } else { sender.Message("There are no permissions assigned to group: " + grpList.Name); } break; default: throw new CommandError("Invalid command " + cmd); } }
/// <summary> /// Allows on the fly variable modifications /// </summary> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public void VariableMan(ISender sender, ArgumentList args) { // var <exec|field> // var field <namespace.type> <fieldname> // var field <namespace.type> <fieldname> <valuetobeset> // var exec <namespace.type> <methodname> //No arguments supported yet var cmd = args.GetString(0); if (cmd == "field" || cmd == "arr") { var type = args.GetString(1); var mem = args.GetString(2); //Find the type var at = Type.GetType(type); if (at == null) { at = System.Reflection.Assembly.GetEntryAssembly().GetType(type); } if (at == null) { at = System.Reflection.Assembly.GetCallingAssembly().GetType(type); } if (at == null) { at = System.Reflection.Assembly.GetExecutingAssembly().GetType(type); } if (at == null) { at = typeof(Terraria.Main).Assembly.GetType(type); } if (at == null) { throw new CommandError("Invalid type: " + type); } //Find the field var am = at.GetField(mem); if (am == null) { throw new CommandError("Invalid field: " + mem); } string val = null; if (cmd != "arr" && args.TryGetString(3, out val)) { object data = GetDataValue(am.FieldType, val); am.SetValue(null, data); var v = am.GetValue(null); if (v != null) { val = v.ToString(); } else { val = "null"; } sender.Message("Value is now: " + val); } else { var v = am.GetValue(null); if (v != null) { if (v.GetType().IsArray) { var index = args.GetInt(3); var obj = (v as Array).GetValue(index); if (obj is Terraria.RemoteClient) { val = ""; var rc = obj as Terraria.RemoteClient; val += $"Id: {rc.Id}\n"; val += $"IsActive: {rc.IsActive}\n"; val += $"IsAnnouncementCompleted: {rc.IsAnnouncementCompleted}\n"; val += $"IsConnected(): {rc.IsConnected()}\n"; val += $"IsReading: {rc.IsReading}\n"; val += $"Name: {rc.Name}\n"; val += $"PendingTermination: {rc.PendingTermination}\n"; val += $"SpamAddBlock: {rc.SpamAddBlock}\n"; val += $"SpamAddBlockMax: {rc.SpamAddBlockMax}\n"; val += $"SpamDeleteBlock: {rc.SpamDeleteBlock}\n"; val += $"SpamDeleteBlockMax: {rc.SpamDeleteBlockMax}\n"; val += $"SpamProjectile: {rc.SpamProjectile}\n"; val += $"SpamProjectileMax: {rc.SpamProjectileMax}\n"; val += $"SpamWater: {rc.SpamWater}\n"; val += $"SpamWaterMax: {rc.SpamWaterMax}\n"; val += $"State: {rc.State}\n"; val += $"StatusCount: {rc.StatusCount}\n"; val += $"StatusMax: {rc.StatusMax}\n"; val += $"StatusText: {rc.StatusText}\n"; val += $"StatusText2: {rc.StatusText2}\n"; val += $"TimeOutTimer: {rc.TimeOutTimer}\n"; #if CUSTOM_SOCKETS if (rc.Socket is OTA.Sockets.ClientConnection) { val += "\n=======================\nClientConnection\n"; var cc = rc.Socket as OTA.Sockets.ClientConnection; val += $"Active: {cc.Active}\n"; val += $"BytesReceived: {cc.BytesReceived}\n"; val += $"BytesSent: {cc.BytesSent}\n"; val += $"IsOTAClient: {cc.IsOTAClient}\n"; val += $"QueueLength: {cc.QueueLength}\n"; val += $"QueueSize: {cc.QueueSize}\n"; //val += $"RemoteAddress: {cc.RemoteAddress}\n"; val += $"SlotId: {cc.SlotId}\n"; } #endif } else { val = obj.ToString(); } } else { val = v.ToString(); } } else { val = "null"; } sender.Message("Value: " + val); } } else if (cmd == "prop") { var type = args.GetString(1); var prop = args.GetString(2); //Find the type var at = Type.GetType(type); if (at == null) { at = System.Reflection.Assembly.GetEntryAssembly().GetType(type); } if (at == null) { at = System.Reflection.Assembly.GetCallingAssembly().GetType(type); } if (at == null) { at = System.Reflection.Assembly.GetExecutingAssembly().GetType(type); } if (at == null) { throw new CommandError("Invalid type: " + type); } //Find the field var am = at.GetProperty(prop); if (am == null) { throw new CommandError("Invalid property: " + prop); } string val = null; if (args.TryGetString(3, out val)) { object data = GetDataValue(am.PropertyType, val); am.SetValue(null, data, null); var v = am.GetValue(null, null); if (v != null) { val = v.ToString(); } else { val = "null"; } sender.Message("Value is now: " + val); } else { var v = am.GetValue(null, null); if (v != null) { val = v.ToString(); } else { val = "null"; } sender.Message("Value: " + val); } } else if (cmd == "exec") { var type = args.GetString(1); var mthd = args.GetString(2); //Find the type var at = Type.GetType(type); if (at == null) { at = System.Reflection.Assembly.GetEntryAssembly().GetType(type); } if (at == null) { at = System.Reflection.Assembly.GetCallingAssembly().GetType(type); } if (at == null) { at = System.Reflection.Assembly.GetExecutingAssembly().GetType(type); } if (at == null) { throw new CommandError("Invalid type: " + type); } //Find the field var am = at.GetMethod(mthd); if (am == null) { throw new CommandError("Invalid method: " + mthd); } var prms = am.GetParameters(); if (prms.Length == 0) { var res = am.Invoke(null, null); var result = res == null ? "null" : res.ToString(); sender.Message("Result: " + result); } else { sender.Message("Arguments are not yet supported for exec"); } } else { sender.Message("Unsupported var command: " + cmd); } }
/// <summary> /// Spawns specified NPC type. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> /// <remarks>This function also allows NPC custom health.</remarks> public void SpawnNPC(ISender sender, ArgumentList args) { //if (Main.stopSpawns && !Program.properties.NPCSpawnsOverride) // throw new CommandError("NPC Spawing is disabled."); //var health = -1; //var customHealth = args.TryPopAny<Int32>("-health", out health); Player player = sender as Player; int amount, offset = -1; if (args.Count > 5) { throw new CommandError("Too many arguments"); } else if (sender is ConsoleSender && args.Count <= 2) { if (!Netplay.anyClients || !Tools.TryGetFirstOnlinePlayer(out player)) { throw new CommandError("No players online."); } } else if (args.Count == 3) { player = args.GetOnlinePlayer(2); } else if (args.Count >= 4) { player = args.GetOnlinePlayer(2); args.TryPopAny <Int32>("-item", out offset); } var npcName = args.GetString(1).ToLower().Trim(); // Get the class id of the npc var npcs = DefinitionManager.FindNPC(npcName); if (npcs == null || npcs.Length == 0) { int npcId; if (Int32.TryParse(npcName, out npcId)) { npcs = DefinitionManager.FindNPC(npcId); if (npcs == null || npcs.Length == 0) { throw new CommandError("No npc exists by type {0}", npcId); } } else { throw new CommandError("No npc exists {0}", npcName); } } npcs = npcs.OrderBy(x => x.Name).ToArray(); if (npcs.Length > 1) { if (offset == -1) { sender.SendMessage("Npcs matching " + npcName + ':'); for (var x = 0; x < npcs.Length; x++) { if (sender is ConsoleSender) { sender.SendMessage($"\t{x}\t- {npcs[x].Name}"); } else { sender.SendMessage($"{x} - {npcs[x].Name}"); } } return; } } else { offset = 0; } var npc = npcs[offset]; if (npc.Boss.HasValue && npc.Boss == true) { throw new CommandError("This NPC can only be summoned by the SPAWNBOSS command."); } try { amount = args.GetInt(0); //if (NPCAmount > Program.properties.SpawnNPCMax && sender is Player) //{ // (sender as Player).Kick("Don't spawn that many."); // return; //} } catch { throw new CommandError("Expected amount to spawn"); } var max = Tools.AvailableNPCSlots; //Perhaps remove a few incase of spawns if (amount > max) { throw new CommandError("Cannot spawn that many, available slots: {0}", max); } string realNPCName = String.Empty; for (int i = 0; i < amount; i++) { Vector2 location = World.GetRandomClearTile(((int)player.position.X / 16), ((int)player.position.Y / 16), 100, 100, 50); int npcIndex = NPC.NewNPC(((int)location.X * 16), ((int)location.Y * 16), npc.Id, 0); //if (customHealth) //{ // Main.npc[npcIndex].life = health; // Main.npc[npcIndex].lifeMax = health; //} Main.npc[npcIndex].netDefaults(npc.NetId); realNPCName = Main.npc[npcIndex].name; } Utils.NotifyAllOps("Spawned " + amount.ToString() + " of " + realNPCName + " [" + player.name + "]", true); }
/// <summary> /// Gives specified item to the specified player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void Give(ISender sender, ArgumentList args) { // /give <stack> <item> [prefix] [player] var index = 0; int stack = args.GetInt(index++); string name = args.GetString(index++); // var max = Tools.AvailableItemSlots; //Perhaps remove a few incase of new drops // if (stack > max) // { // stack = max; // Set to Tools.AvailableItemSlots because number given was larger than this. // } int id; var results = Int32.TryParse(name, out id) ? DefinitionManager.FindItem(id) : DefinitionManager.FindItem(name); if (results != null && results.Length > 0) { if (results.Length > 1) { throw new CommandError(String.Format("More than 1 item found, total is: {0}", results.Length)); } var item = results[0]; string prefix; if (args.TryGetString(index, out prefix)) { try { Affix afx; if (Enum.TryParse(prefix, out afx)) { item.Prefix = (int)afx; index++; } } catch (ArgumentException) { throw new CommandError(String.Format("Error, the Prefix you entered was not found: {0}", args.GetString(3))); } } Player receiver; if (!args.TryGetOnlinePlayer(index, out receiver)) { if (sender is Player) { receiver = sender as Player; } else { throw new CommandError("Expected an online player"); } } receiver.GiveItem(item.Id, stack, item.MaxStack, item.NetId, item.Prefix); } else { throw new CommandError(String.Format("No item known by: {0}", name)); } }
/// <summary> /// Spawns specified NPC type. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> /// <remarks>This function also allows NPC custom health.</remarks> public void SpawnNPC(ISender sender, ArgumentList args) { //if (Main.stopSpawns && !Program.properties.NPCSpawnsOverride) // throw new CommandError("NPC Spawing is disabled."); //var health = -1; //var customHealth = args.TryPopAny<Int32>("-health", out health); Player player = sender as Player; int amount; if (args.Count > 4) throw new CommandError("Too many arguments"); else if (sender is ConsoleSender && args.Count <= 2) { if (!Netplay.anyClients || !Tools.TryGetFirstOnlinePlayer(out player)) throw new CommandError("No players online."); } else if (args.Count >= 3) player = args.GetOnlinePlayer(2); var npcName = args.GetString(1).ToLower().Trim(); // Get the class id of the npc var npcs = DefinitionManager.FindNPC(npcName); if (npcs.Length == 0) throw new CommandError("No npc exists by the name {0}", npcName); else if (npcs.Length > 1) { bool first; args.TryGetBool(3, out first); if (!first) throw new CommandError("Too many results for {0}, total count {1}", npcName, npcs.Length); } var npc = npcs[0]; if (npc.Boss.HasValue && npc.Boss == true) throw new CommandError("This NPC can only be summoned by the SPAWNBOSS command."); try { amount = args.GetInt(0); //if (NPCAmount > Program.properties.SpawnNPCMax && sender is Player) //{ // (sender as Player).Kick("Don't spawn that many."); // return; //} } catch { throw new CommandError("Expected amount to spawn"); } var max = Tools.AvailableNPCSlots; //Perhaps remove a few incase of spawns if (amount > max) throw new CommandError("Cannot spawn that many, available slots: {0}", max); string realNPCName = String.Empty; for (int i = 0; i < amount; i++) { Vector2 location = World.GetRandomClearTile(((int)player.position.X / 16), ((int)player.position.Y / 16), 100, 100, 50); int npcIndex = NPC.NewNPC(((int)location.X * 16), ((int)location.Y * 16), npc.Id, 0); //if (customHealth) //{ // Main.npc[npcIndex].life = health; // Main.npc[npcIndex].lifeMax = health; //} Main.npc[npcIndex].netDefaults(npc.NetId); realNPCName = Main.npc[npcIndex].name; } Tools.NotifyAllOps("Spawned " + amount.ToString() + " of " + realNPCName + " [" + player.name + "]", true); }
/// <summary> /// Spawns specified NPC type. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> /// <remarks>This function also allows NPC custom health.</remarks> public void SpawnNPC(ISender sender, ArgumentList args) { //if (Main.stopSpawns && !Program.properties.NPCSpawnsOverride) // throw new CommandError("NPC Spawing is disabled."); //var health = -1; //var customHealth = args.TryPopAny<Int32>("-health", out health); Player player = sender as Player; int amount, offset = -1; if (args.Count > 5) throw new CommandError("Too many arguments"); else if (sender is ConsoleSender && args.Count <= 2) { if (!Netplay.anyClients || !Tools.TryGetFirstOnlinePlayer(out player)) throw new CommandError("No players online."); } else if (args.Count == 3) player = args.GetOnlinePlayer(2); else if (args.Count >= 4) { player = args.GetOnlinePlayer(2); args.TryPopAny<Int32>("-item", out offset); } var npcName = args.GetString(1).ToLower().Trim(); // Get the class id of the npc var npcs = DefinitionManager.FindNPC(npcName); if (npcs == null || npcs.Length == 0) { int npcId; if (Int32.TryParse(npcName, out npcId)) { npcs = DefinitionManager.FindNPC(npcId); if (npcs == null || npcs.Length == 0) { throw new CommandError("No npc exists by type {0}", npcId); } } else throw new CommandError("No npc exists {0}", npcName); } npcs = npcs.OrderBy(x => x.Name).ToArray(); if (npcs.Length > 1) { if (offset == -1) { sender.SendMessage("Npcs matching " + npcName + ':'); for (var x = 0; x < npcs.Length; x++) { if (sender is ConsoleSender) { sender.SendMessage($"\t{x}\t- {npcs[x].Name}"); } else { sender.SendMessage($"{x} - {npcs[x].Name}"); } } return; } } else offset = 0; var npc = npcs[offset]; if (npc.Boss.HasValue && npc.Boss == true) throw new CommandError("This NPC can only be summoned by the SPAWNBOSS command."); try { amount = args.GetInt(0); //if (NPCAmount > Program.properties.SpawnNPCMax && sender is Player) //{ // (sender as Player).Kick("Don't spawn that many."); // return; //} } catch { throw new CommandError("Expected amount to spawn"); } var max = Tools.AvailableNPCSlots; //Perhaps remove a few incase of spawns if (amount > max) throw new CommandError("Cannot spawn that many, available slots: {0}", max); string realNPCName = String.Empty; for (int i = 0; i < amount; i++) { Vector2 location = World.GetRandomClearTile(((int)player.position.X / 16), ((int)player.position.Y / 16), 100, 100, 50); int npcIndex = NPC.NewNPC(((int)location.X * 16), ((int)location.Y * 16), npc.Id, 0); //if (customHealth) //{ // Main.npc[npcIndex].life = health; // Main.npc[npcIndex].lifeMax = health; //} Main.npc[npcIndex].netDefaults(npc.NetId); realNPCName = Main.npc[npcIndex].name; } Utils.NotifyAllOps("Spawned " + amount.ToString() + " of " + realNPCName + " [" + player.name + "]", true); }
/// <summary> /// Sets the time in the game. /// </summary> /// <param name="server">Current Server instance</param> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public static void Time(Server server, ISender sender, ArgumentList args) { Double Time; if (args.TryParseOne<Double>("-set", out Time)) { server.World.setTime(Time, true); } else { String caseType = args.GetString(0); switch (caseType) { case "day": { server.World.setTime(13500.0); break; } case "dawn": { server.World.setTime(0); break; } case "dusk": { server.World.setTime(0, false, false); break; } case "noon": { server.World.setTime(27000.0); break; } case "night": { server.World.setTime(16200.0, false, false); break; } case "-now": { String AP = "AM"; double time = Main.time; if (!Main.dayTime) { time += 54000.0; } time = (time / 86400.0 * 24.0) - 19.5; if (time < 0.0) { time += 24.0; } if (time >= 12.0) { AP = "PM"; } int Hours = (int)time; double Minutes = time - (double)Hours; String MinuteString = (Minutes * 60.0).ToString(); if (Minutes < 10.0) { MinuteString = "0" + MinuteString; } if (Hours > 12) { Hours -= 12; } if (Hours == 0) { Hours = 12; } if (MinuteString.Length > 2) { MinuteString = MinuteString.Substring(0, 2); } sender.sendMessage("Current Time: " + Hours + ":" + MinuteString + " " + AP); return; } default: { sender.sendMessage("Please review that command."); return; } } } NetMessage.SendData((int)Packet.WORLD_DATA); //Update Data server.notifyAll("Time set to " + Server.time.ToString() + " by " + sender.Name); }
void ManageApi(ISender sender, ArgumentList args) { if (!Storage.IsAvailable) throw new CommandError("No permissions plugin or data plugin is attached"); var a = 0; string name, pass, type, value; APIAccount acc = null; var cmd = args.GetString(a++); switch (cmd) { case "addaccount": //api addaccount "username" "password" if (!args.TryGetString(a++, out name)) throw new CommandError("Expected username after [" + cmd + "]"); if (!args.TryGetString(a++, out pass)) throw new CommandError("Expected password after username"); acc = APIAccountManager.FindByName(name); if (acc == null) { acc = APIAccountManager.Create(name, pass); if (acc.Id > 0) { sender.SendMessage("Successfully created account.", R: 0, B: 0); } else { sender.SendMessage("Failed to create account.", G: 0, B: 0); } } else { throw new CommandError("Existing API account found by " + name); } break; case "removeaccount": //api removeaccount "username" if (!args.TryGetString(a++, out name)) throw new CommandError("Expected username after [" + cmd + "]"); acc = APIAccountManager.FindByName(name); if (acc != null) { if (APIAccountManager.DeleteAccount(acc.Id)) { sender.SendMessage("Successfully removed account.", R: 0, B: 0); } else { sender.SendMessage("Failed to remove account.", G: 0, B: 0); } } else { throw new CommandError("No API account found by " + name); } break; case "addrole": //api addrole "account" "type" "value" if (!args.TryGetString(a++, out name)) throw new CommandError("Expected username after [" + cmd + "]"); if (!args.TryGetString(a++, out type)) throw new CommandError("Expected type after username"); if (!args.TryGetString(a++, out value)) throw new CommandError("Expected value after type"); acc = APIAccountManager.FindByName(name); if (acc != null) { var role = APIAccountManager.AddType(acc.Id, type, value); if (role != null && role.Id > 0) { sender.SendMessage("Successfully added role account.", R: 0, B: 0); } else { sender.SendMessage("Failed to add role to account.", G: 0, B: 0); } } else { throw new CommandError("No API account found by " + name); } break; case "removerole": //api removerole "account" "type" "value" if (!args.TryGetString(a++, out name)) throw new CommandError("Expected username after [" + cmd + "]"); if (!args.TryGetString(a++, out type)) throw new CommandError("Expected type after username"); if (!args.TryGetString(a++, out value)) throw new CommandError("Expected value after type"); acc = APIAccountManager.FindByName(name); if (acc != null) { var role = APIAccountManager.DeleteType(acc.Id, type, value); if (role) { sender.SendMessage("Successfully removed role account.", R: 0, B: 0); } else { sender.SendMessage("Failed to removed role from account.", G: 0, B: 0); } } else { throw new CommandError("No API account found by " + name); } break; case "search": //api search "part" if (!args.TryGetString(a++, out name)) throw new CommandError("Expected part of a acount name after [" + cmd + "]"); var matches = APIAccountManager.FindAccountsByPrefix(name); if (matches != null && matches.Length > 0) { sender.Message("Matches:"); foreach (var mth in matches) { sender.Message("\t" + mth); } } else { sender.Message("There are no registered accounts matching " + name); } break; default: throw new CommandError("Invalid command " + cmd); } }
internal static void RConCommand(ISender sender, ArgumentList args) { string name, pass; if (args.TryPop("add") && args.TryParseTwo(out name, out pass)) { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } var password = Hash(name, pass); LoginDatabase.SetValue(name, password); LoginDatabase.Save(); ProgramLog.Log("User `{0}` was added to the RCON Database.", name); } else if (args.TryParseOne("cut", out name)) { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) rcon.Close(); } ProgramLog.Admin.Log("Cut all remote console connections from {0}.", name); } else if (args.TryParseOne("ban", out name)) { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } LoginDatabase.SetValue(name, null); var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) rcon.Close(); } ProgramLog.Admin.Log("Cut all remote console connections from {0} and revoked credentials.", name); } else if (args.Count == 1 && args.GetString(0) == "list") { foreach (var rcon in clients) { sender.SendMessage(String.Format("{0} {1}", rcon.Id, rcon.state)); } } else if (args.Count == 1 && args.GetString(0) == "load") { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } LoginDatabase.Load(); ProgramLog.Admin.Log("Reloaded remote console login database."); } else { throw new CommandError(""); } }
/// <summary> /// Sets OP status to a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void OpPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); if (Storage.IsAvailable) { var existing = Authentication.GetPlayer(playerName); if (existing == null && (args.Contains("-c") || args.Contains("-create"))) { var password = args.GetString(1); existing = Authentication.CreatePlayer(playerName, password, true); Utils.NotifyAllOps("Opping " + playerName + " [" + sender.SenderName + "]", true); var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("You are now a server operator.", Color.Green); player.SetOp(true); player.SetAuthentication(player.name, "tdsm"); } sender.Message("Op success", Color.DarkGreen); } else if (existing != null) { if (existing.Operator) throw new CommandError("Player is already an operator"); if (Authentication.UpdatePlayer(playerName, null, op: true)) { Utils.NotifyAllOps("Opping " + playerName + " [" + sender.SenderName + "]", true); var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("You are now a server operator.", Color.Green); player.SetOp(true); player.SetAuthentication(player.name, "tdsm"); } sender.Message("Op success", Color.DarkGreen); } else { sender.Message("Failed to op player", Color.DarkRed); } } else { sender.Message("No user found by " + playerName, Color.DarkRed); sender.Message("Please use the `user` command or add the -create switch", Color.DarkRed); } } else { var password = args.GetString(1); Utils.NotifyAllOps("Opping " + playerName + " [" + sender.SenderName + "]", true); Core.Ops.Add(playerName, password); var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("You are now a server operator.", Color.Green); player.SetOp(true); player.SetAuthentication(player.name, "tdsm"); } if (!Core.Ops.Save()) { Utils.NotifyAllOps("Failed to save op list [" + sender.SenderName + "]", true); return; } } }
void UserPermission(ISender sender, ArgumentList args) { if (!Storage.IsAvailable) throw new CommandError("No permissions plugin or data plugin is attached"); int a = 0; string username, groupName, node, password; DbPlayer user; Group grp; bool deny, op; var cmd = args.GetString(a++); switch (cmd) { case "addgroup": //user addgroup "username" "group" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after username"); user = Authentication.GetPlayer(username); if (null == user) throw new CommandError("No user found by: " + username); grp = Storage.FindGroup(groupName); if (grp == null) throw new CommandError("Group does not exist: " + groupName); if (Storage.AddUserToGroup(user.Name, grp.Name)) { sender.Message(String.Format("Successfully added {0} to group {1} ", user.Name, grp.Name), Color.Green); } else { sender.Message(String.Format("Failed to add {0} from group {1} ", user.Name, grp.Name), Color.Red); } break; case "removegroup": //user removegroup "username" "group" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after username"); user = Authentication.GetPlayer(username); if (null == user) throw new CommandError("No user found by: " + username); grp = Storage.FindGroup(groupName); if (grp == null) throw new CommandError("Group does not exist: " + groupName); if (Storage.RemoveUserFromGroup(user.Name, grp.Name)) { sender.Message(String.Format("Successfully removed {0} to group {1} ", user.Name, grp.Name), Color.Green); } else { sender.Message(String.Format("Failed to remove {0} from group {1} ", user.Name, grp.Name), Color.Red); } break; case "addnode": //user addnode "username" "node" "deny" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); if (!args.TryGetString(a++, out node)) throw new CommandError("Expected node name after username"); if (!args.TryGetBool(a++, out deny)) deny = false; user = Authentication.GetPlayer(username); if (null == user) throw new CommandError("No user found by: " + username); if (Storage.AddNodeToUser(user.Name, node, deny ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully added {0} to user {1} ", node, user.Name), Color.Green); } else { sender.Message(String.Format("Failed to add {0} from user {1} ", node, user.Name), Color.Red); } break; case "removenode": //user removenode "username" "node" "deny" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); if (!args.TryGetString(a++, out node)) throw new CommandError("Expected node name after username"); if (!args.TryGetBool(a++, out deny)) deny = false; user = Authentication.GetPlayer(username); if (null == user) throw new CommandError("No user found by: " + username); if (Storage.RemoveNodeFromUser(user.Name, node, deny ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully removed {0} to user {1} ", node, user.Name), Color.Green); } else { sender.Message(String.Format("Failed to remove {0} from user {1} ", node, user.Name), Color.Red); } break; case "groups": case "listgroups": if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); user = Authentication.GetPlayer(username); if (null == user) throw new CommandError("No user found by: " + username); var groups = Storage.UserGroupList(username); if (groups != null && groups.Length > 0) { sender.Message("Current groups:"); foreach (var gps in groups) { sender.Message("\t" + gps); } } else { sender.Message("There are no registered groups for user " + user.Name); } break; case "nodes": case "listnodes": if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); user = Authentication.GetPlayer(username); if (null == user) throw new CommandError("No user found by: " + username); var nodes = Storage.UserNodes(username); if (nodes != null && nodes.Length > 0) { sender.Message("Current permissions for user {0}:", user.Name); foreach (var nd in nodes) { sender.Message("\t{0}\t- {1}", (nd.Permission == Permission.Denied) ? "Denied" : "Allowed", nd.Node); } } else { sender.Message("There are no permissions assigned to user: "******"search": //user search "part" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected part of a users name after [" + cmd + "]"); var matches = Authentication.FindPlayersByPrefix(username, true); if (matches != null && matches.Length > 0) { sender.Message("Matches:"); foreach (var mth in matches) { sender.Message("\t" + mth); } } else { sender.Message("There are no registered users matching " + username); } break; case "add": //user add "username" "password" [-op | groupname] if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); if (!args.TryGetString(a++, out password)) throw new CommandError("Expected password name after username"); grp = null; groupName = String.Empty; if (!args.TryGetBool(a, out op)) { if (!args.TryGetString(a++, out groupName)) { groupName = String.Empty; } } else a++; op = groupName.ToLower() == "-op" || groupName.ToLower() == "op"; if (!op && args.Count == 4) { grp = Storage.FindGroup(groupName); if (grp == null || grp.Id == 0) sender.Message("No group found by {0}", groupName); } var existing = Authentication.GetPlayer(username); if (existing == null) { if (Authentication.CreatePlayer(username, password, op) != null) { if (op) { sender.Message("Successfully created user as operator: " + username); } else { if (args.Count == 4) { if (grp != null) { if (Storage.AddUserToGroup(username, grp.Name)) { sender.Message("Successfully created user {0} as a member of group {1}", Color.Green, username, grp.Name); } else { sender.Message("Successfully created user {0}, but failed associate group {1}", Color.Green, username, grp.Name); } } } else { sender.Message("Successfully created user " + username, Color.Green); } } } else throw new CommandError("User failed to be created"); } else throw new CommandError("A user already exists by the name " + username); break; case "update": //user update "username" "password" "op" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); if (!args.TryGetString(a++, out password)) throw new CommandError("Expected password name after username"); args.TryGetBool(a++, out op); var updatee = Authentication.GetPlayer(username); if (updatee != null) { if (Authentication.UpdatePlayer(username, password, op)) { if (op) { sender.Message("Successfully updated user as operator: " + username); } else { sender.Message("Successfully updated user " + username); } } else throw new CommandError("User failed to be updated"); } else throw new CommandError("No user exists by the name " + username); break; case "remove": //user remove "username" if (!args.TryGetString(a++, out username)) throw new CommandError("Expected username name after [" + cmd + "]"); var delUser = Authentication.GetPlayer(username); if (delUser != null) { if (Authentication.DeletePlayer(username)) { sender.Message("Successfully removed user " + username); } else throw new CommandError("User failed to be removed"); } else throw new CommandError("Cannot find user " + username); break; default: throw new CommandError("Invalid command " + cmd); } }
/// <summary> /// Spawns specified NPC type. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> /// <remarks>This function also allows NPC custom health.</remarks> public static void SpawnNPC(ISender sender, ArgumentList args) { if (Main.stopSpawns && !Program.properties.NPCSpawnsOverride) throw new CommandError("NPC Spawing is disabled."); var health = -1; var customHealth = args.TryPopAny<Int32>("-health", out health); Player player = sender as Player; int NPCAmount; if (args.Count > 3) throw new CommandError(Languages.TooManyArguments); else if (sender is ConsoleSender && args.Count <= 2) { if (!NetPlay.anyClients || !Server.TryGetFirstOnlinePlayer(out player)) throw new CommandError(Languages.NobodyOnline); } else if (args.Count == 3) player = args.GetOnlinePlayer(2); var npcName = args.GetString(1).ToLower().Trim(); // Get the class id of the npc int realNPCId = 0; NPC fclass = Registries.NPC.FindClass(npcName); if (fclass.Name != String.Empty) realNPCId = fclass.Type; else throw new CommandError(Languages.NPCDoesntExist); try { NPCAmount = args.GetInt(0); if (NPCAmount > Program.properties.SpawnNPCMax && sender is Player) { (sender as Player).Kick(Languages.DontSpawnThatMany); return; } } catch { throw new CommandError(Languages.ExpectedSpawnInteger); } string realNPCName = String.Empty; for (int i = 0; i < NPCAmount; i++) { Vector2 location = World.GetRandomClearTile(((int)player.Position.X / 16), ((int)player.Position.Y / 16), 100, true, 100, 50); int npcIndex = NPC.NewNPC(((int)location.X * 16), ((int)location.Y * 16), fclass.Name, 0, Main.SpawnsOverride); if (customHealth) { Main.npcs[npcIndex].life = health; Main.npcs[npcIndex].lifeMax = health; } realNPCName = Main.npcs[npcIndex].Name; } Server.notifyOps("Spawned " + NPCAmount.ToString() + " of " + realNPCName + " [" + player.Name + "]", true); }
/// <summary> /// Summon a Boss /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void SummonBoss(ISender sender, ArgumentList args) { var count = args.GetInt(0); var bossName = args.GetString(1).ToLower(); Player target; if (!args.TryGetOnlinePlayer(2, out target)) { if (sender is Player) { target = sender as Player; } else { target = Main.player.Where(x => x.active).Random(); if (null == target) { throw new CommandError("No players online"); } } } // int type = -1, type1 = -1; // string name = null; var queue = new Queue <Boss>(); switch (bossName) { case "wyvern": // type = 87; queue.Enqueue(new Boss() { type = 87 }); break; case "brain": case "brain of cthulhu": // type = 266; queue.Enqueue(new Boss() { type = 266 }); break; // case "crimson mimic": // type = 474; // break; case "corrupt mimic": // type = 473; queue.Enqueue(new Boss() { type = 473 }); break; // case "hallowed mimic": // type = 475; // break; case "duke fishron": case "duke": case "fishron": // type = 370; queue.Enqueue(new Boss() { type = 370 }); break; case "everscream": World.SetTime(16200.0, false); // type = 344; queue.Enqueue(new Boss() { type = 344 }); break; case "eye": case "cthulhu": case "eye of cthulhu": World.SetTime(16200.0, false); // type = 4; queue.Enqueue(new Boss() { type = 4 }); break; case "dutchman": case "flying dutchman": // type = 491; queue.Enqueue(new Boss() { type = 491 }); break; case "golem": // type = 245; queue.Enqueue(new Boss() { type = 245 }); break; case "goblin summoner": // type = 471; queue.Enqueue(new Boss() { type = 471 }); break; case "king": case "king slime": // type = 50; queue.Enqueue(new Boss() { type = 50 }); break; case "ice golem": // type = 243; queue.Enqueue(new Boss() { type = 243 }); break; case "ice queen": World.SetTime(16200.0, false); // type = 345; queue.Enqueue(new Boss() { type = 345 }); break; case "lunatic": case "cultist": case "lunatic cultist": // type = 439; queue.Enqueue(new Boss() { type = 439 }); break; case "saucer": case "martian saucer": // type = 395; queue.Enqueue(new Boss() { type = 395 }); break; case "moon": case "moon lord": // type = 398; queue.Enqueue(new Boss() { type = 398 }); break; case "mothron": if (!Main.eclipse) { throw new CommandError("Mothron can only be spawned during a solar eclipse. See the worldevent command."); } // type = 477; queue.Enqueue(new Boss() { type = 477 }); break; case "wood": case "mourning wood": World.SetTime(16200.0, false); // type = 325; queue.Enqueue(new Boss() { type = 325 }); break; case "paladin": // type = 290; queue.Enqueue(new Boss() { type = 290 }); break; case "captain": case "pirate": case "pirate captain": World.SetTime(16200.0, false); // type = 216; queue.Enqueue(new Boss() { type = 216 }); break; case "plantera": // type = 262; queue.Enqueue(new Boss() { type = 262 }); break; case "pumpking": World.SetTime(16200.0, false); // type = 327; queue.Enqueue(new Boss() { type = 327 }); break; case "queen": case "queen bee": // type = 222; queue.Enqueue(new Boss() { type = 222 }); break; case "santa": case "santa nk1": case "santa-nk1": World.SetTime(16200.0, false); // type = 346; queue.Enqueue(new Boss() { type = 346 }); break; case "skeletron": World.SetTime(16200.0, false); // type = 35; queue.Enqueue(new Boss() { type = 35 }); break; case "prime": case "skeletron prime": // type = 127; queue.Enqueue(new Boss() { type = 127 }); break; case "nebula": case "nebula pillar": // type = 507; queue.Enqueue(new Boss() { type = 507 }); break; case "solar": case "solar pillar": // type = 517; queue.Enqueue(new Boss() { type = 517 }); break; case "stardust": case "stardust pillar": // type = 493; queue.Enqueue(new Boss() { type = 493 }); break; case "vortex": case "vortex pillar": // type = 422; queue.Enqueue(new Boss() { type = 422 }); break; case "destroyer": case "the destroyer": World.SetTime(16200.0, false); // type = 134; queue.Enqueue(new Boss() { type = 134 }); break; case "twins": case "the twins": World.SetTime(16200.0, false); // type = 125; // type1 = 126; queue.Enqueue(new Boss() { type = 125, name = "The Twins" }); queue.Enqueue(new Boss() { type = 126, ignore = true }); break; case "eater": case "eater of worlds": // type = 13; queue.Enqueue(new Boss() { type = 13 }); break; case "wall": case "flesh": case "wall of flesh": if (Main.wof > 0 && Main.npc[Main.wof].active) { throw new CommandError("The Wall Of Flesh is already active"); } if (target.position.Y / 16 < (float)(Main.maxTilesY - 205)) //As per NPC.SpawnWOF { throw new CommandError("Player must be in The Underworld to spawn the Eater Of Worlds"); } // type = 113; queue.Enqueue(new Boss() { type = 113 }); break; case "deathcradle": count = 1; var items = new int[] { 87, 266, 473, 370, 344, 4, 491, 245, 471, 50, 243, 345, 439, 395, 398, 477, 325, 290, 216, 262, 327, 222, 346, 35, 127, 507, 517, 493, 422, 134, 125, 126, 13 }; World.SetTime(16200.0, false); foreach (var item in items) { queue.Enqueue(new Boss() { type = item, ignore = true }); } Core._likeABoss = true; Tools.NotifyAllPlayers("Easter egg found: Like a boss mini game!", Color.Purple, true); break; default: throw new CommandError("Unknown boss: " + bossName); } while (count-- > 0) { while (queue.Count > 0) { var boss = queue.Dequeue(); var position = World.GetRandomClearTile(target.position.X / 16f, target.position.Y / 16f); var id = NPC.NewNPC((int)(position.X * 16f), (int)(position.Y * 16f), boss.type); Main.npc[id].SetDefaults(boss.type); Main.npc[id].SetDefaults(Main.npc[id].name); if (count == 0 && !boss.ignore) { var tms = String.Empty; if (count > 1) { tms = " " + count + " times"; } Tools.NotifyAllPlayers((boss.name ?? Main.npc[id].name) + " [" + boss.type + "]" + " summoned by " + sender.SenderName + tms, Color.Purple, true); } } } }
/// <summary> /// Gives specified item to the specified player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public static void Give(ISender sender, ArgumentList args) { // /give <player> <stack> <name> string _prefix; args.TryPopAny("-prefix", out _prefix); byte prefix; if (!Byte.TryParse(_prefix, out prefix)) { Affix affix; if (!AffixExtensions.Parse(_prefix ?? String.Empty, out affix, true)) prefix = 0; else prefix = (byte)affix; } Player receiver = args.GetOnlinePlayer(0); int stack = args.GetInt(1); string NameOrId = args.GetString(2); List<ItemInfo> itemlist; if (Server.TryFindItemByName(NameOrId, out itemlist) && itemlist.Count > 0) { if (itemlist.Count > 1) throw new CommandError(String.Format(Languages.MoreThanOneItemFoundNameId, itemlist.Count)); var item = itemlist[0]; var index = receiver.GiveItem(item.Type, stack, sender, item.NetID, true, prefix); if (item.NetID < 0) Main.item[index] = Item.netDefaults(item.NetID); Main.item[index].Prefix = prefix; } else { int Id = -1; try { Id = Int32.Parse(NameOrId); } catch { throw new CommandError(String.Format(Languages.MoreThanOneItemFoundNameId, itemlist.Count)); } if (Server.TryFindItemByType(Id, out itemlist) && itemlist.Count > 0) { if (itemlist.Count > 1) throw new CommandError(String.Format(Languages.MoreThanOneItemFoundType, itemlist.Count)); //receiver.GiveItem(itemlist[0].Type, stack, sender); var item = itemlist[0]; var index = receiver.GiveItem(item.Type, stack, sender, item.NetID, true, prefix); if (item.NetID < 0) Main.item[index] = Item.netDefaults(item.NetID); Main.item[index].Prefix = prefix; } else { throw new CommandError(String.Format(Languages.MoreThanOneItemFoundNameId, "no")); } } }
/// <summary> /// Gives specified item to the specified player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void Give(ISender sender, ArgumentList args) { // /give <player> <stack> <name> Player receiver = args.GetOnlinePlayer(0); int stack = args.GetInt(1); string name = args.GetString(2); var max = Tools.AvailableItemSlots; //Perhaps remove a few incase of new drops if (stack > max) { stack = max; // Set to Tools.AvailableItemSlots because number given was larger than this. } var results = DefinitionManager.FindItem(name); if (results != null && results.Length > 0) { if (results.Length > 1) throw new CommandError(String.Format("More than 1 item found, total is: {0}", results.Length)); var item = results[0]; var index = receiver.GiveItem(item.Id, stack, sender, item.NetId, true, item.Prefix); if (item.NetId < 0) Main.item[index].netDefaults(item.NetId); Main.item[index].Prefix(item.Prefix); } else throw new CommandError(String.Format("No item known by: {0}", name)); }
/// <summary> /// Gives specified item to the specified player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public static void Give(ISender sender, ArgumentList args) { // /give <player> <stack> <name> Player receiver = args.GetOnlinePlayer(0); int stack = args.GetInt(1); string NameOrId = args.GetString(2); List<Int32> itemlist; if (Server.TryFindItemByName(NameOrId, out itemlist) && itemlist.Count > 0) { if (itemlist.Count > 1) throw new CommandError("There were {0} Items found regarding the specified name", itemlist.Count); foreach (int id in itemlist) receiver.GiveItem(id, stack, sender); } else { int Id = -1; try { Id = Int32.Parse(NameOrId); } catch { throw new CommandError("There were {0} Items found regarding the specified Item Id/Name", itemlist.Count); } if (Server.TryFindItemByType(Id, out itemlist) && itemlist.Count > 0) { if (itemlist.Count > 1) throw new CommandError("There were {0} Items found regarding the specified Type Id", itemlist.Count); foreach (int id in itemlist) receiver.GiveItem(id, stack, sender); } else { throw new CommandError("There were no Items found regarding the specified Item Id/Name"); } } }
/// <summary> /// Sets OP status to a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void OpPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); var password = args.GetString(1); Tools.NotifyAllOps("Opping " + playerName + " [" + sender.SenderName + "]", true); Ops.Add(playerName, password); //Player player; //if (args.TryGetOnlinePlayer(0, out player)) //{ // playerName = player.Name; // player.SendMessage("You are now a server operator.", Color.Green); // player.Op = true; //} var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("You are now a server operator.", Color.Green); player.Op = true; } if (!Ops.Save()) { Tools.NotifyAllOps("Failed to save op list [" + sender.SenderName + "]", true); return; } }
internal static void RConCommand(ISender sender, ArgumentList args) { string name, pass; if (args.TryPop("add") && args.TryParseTwo(out name, out pass)) { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } var password = Hash(name, pass); LoginDatabase.SetValue(name, password); LoginDatabase.Save(); ProgramLog.Log("User `{0}` was added to the RCON Database.", name); } else if (args.TryParseOne("cut", out name)) { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) { rcon.Close(); } } ProgramLog.Admin.Log("Cut all remote console connections from {0}.", name); } else if (args.TryParseOne("ban", out name)) { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } LoginDatabase.SetValue(name, null); var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) { rcon.Close(); } } ProgramLog.Admin.Log("Cut all remote console connections from {0} and revoked credentials.", name); } else if (args.Count == 1 && args.GetString(0) == "list") { foreach (var rcon in clients) { sender.SendMessage(String.Format("{0} {1}", rcon.Id, rcon.state)); } } else if (args.Count == 1 && args.GetString(0) == "load") { if (sender is Player || sender is RConSender) { sender.SendMessage("Permissions error", 255, 238, 130, 238); return; } LoginDatabase.Load(); ProgramLog.Admin.Log("Reloaded remote console login database."); } else { throw new CommandError(""); } }
/// <summary> /// Sets the time in the game. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void Time(ISender sender, ArgumentList args) { double time; WorldTime text; if (args.TryParseOne <Double>("-set", out time) || args.TryParseOne <Double>("set", out time)) { if (time >= WorldTime.TimeMin && time <= WorldTime.TimeMax) { World.SetTime(time); } else { sender.SendMessage(String.Format("Invalid time specified, must be from {0} to {1}", WorldTime.TimeMin, WorldTime.TimeMax)); return; } } else if (args.TryParseOne <WorldTime>("-set", out text) || args.TryParseOne <WorldTime>("set", out text)) { time = text.GameTime; World.SetParsedTime(time); } else { string caseType = args.GetString(0); switch (caseType) { case "day": { World.SetTime(13500.0); break; } case "dawn": { World.SetTime(0); break; } case "dusk": { World.SetTime(0, false); break; } case "noon": { World.SetTime(27000.0); break; } case "night": { World.SetTime(16200.0, false); break; } case "?": case "now": case "-now": { sender.Message("Current time: " + WorldTime.Parse(World.GetParsableTime()).ToString()); return; } default: { sender.Message("Please review your command"); return; } } } NetMessage.SendData((int)Packet.WORLD_DATA); //Update Data var current = WorldTime.Parse(World.GetParsableTime()).Value; Tools.NotifyAllPlayers(String.Format("Time set to {0} ({1}) by {2}", current.ToString(), current.GameTime, sender.SenderName), Color.Green); }
/// <summary> /// Spawns specified NPC type. /// </summary> /// <param name="server">Current Server instance</param> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public static void SpawnNPC(Server server, ISender sender, ArgumentList args) { Player player = sender as Player; if (args.Count > 3) { throw new CommandError("Too many arguments. NPC and player names with spaces require quotes."); } else if (sender is ConsoleSender && args.Count <= 2) { throw new CommandError("As console you need to specify the player to spawn near."); } else if (args.Count == 3) { player = args.GetOnlinePlayer(2); } String npcName = args.GetString(1).ToLower().Trim(); // Get the class id of the npc Int32 realNPCId = 0; NPC fclass = Registries.NPC.FindClass(npcName); if (fclass.type != Registries.NPC.Default.type) { realNPCId = fclass.Type; } else { try { realNPCId = Int32.Parse(npcName); } catch { throw new CommandError("Specified NPC does not exist"); } } int NPCAmount = 0; try { NPCAmount = Int32.Parse(args[0]); if (NPCAmount > Program.properties.SpawnNPCMax && sender is Player) { (sender as Player).Kick ("Don't spawn that many."); return; } } catch { throw new CommandError("Expected integer for number to spawn."); } String realNPCName = ""; for (int i = 0; i < NPCAmount; i++) { Vector2 location = World.GetRandomClearTile(((int)player.Position.X / 16), ((int)player.Position.Y / 16), 100, true, 100, 50); int npcIndex = NPC.NewNPC(((int)location.X * 16), ((int)location.Y * 16), fclass.Name); //Registries.NPC.Alter(Main.npcs[npcIndex], fclass.Name); realNPCName = Main.npcs[npcIndex].Name; } Program.server.notifyOps("Spawned " + NPCAmount.ToString() + " of " + realNPCName + " {" + player.Name + "}", true); }
/////// <summary> /////// Adds or removes specified player to/from the white list. /////// </summary> /////// <param name="sender">Sending player</param> /////// <param name="args">Arguments sent with command</param> ////public static void WhiteList(ISender sender, ArgumentList args) ////{ //// // /whitelist <add:remove> <player> //// string Exception, Type = String.Empty; //// if (args.TryParseOne<String>(Languages.Add, out Exception)) //// { //// Server.WhiteList.addException(Exception); //// Type = Languages.Added; //// } //// else if (args.TryParseOne<String>(Languages.Remove, out Exception)) //// { //// Server.WhiteList.removeException(Exception); //// Type = Languages.RemovedFrom; //// } //// else //// { //// sender.Message(Languages.PleaseReview); //// return; //// } //// Tools.NotifyAllOps(Exception + " was " + Type + " the Whitelist [" + sender.SenderName + "]", true); //// if (!Server.WhiteList.Save()) //// { //// Tools.NotifyAllOps(Languages.WhilelistFailedSave + sender.SenderName + "'s " + Languages.Command, true); //// } ////} ///// <summary> ///// Adds a player or ip (Exception) to the ban list. ///// </summary> ///// <param name="sender">Sending player</param> ///// <param name="args">Arguments sent with command</param> //public static void Ban(ISender sender, ArgumentList args) //{ // Player banee; // string playerName = null; // if (args.TryGetOnlinePlayer(0, out banee)) // { // playerName = banee.Name; // banee.Kick(Languages.Ban_You); // Server.BanList.addException(Netplay.slots[banee.whoAmi]. // remoteAddress.Split(':')[0]); // } // else if (!args.TryGetString(0, out playerName)) // { // throw new CommandError(Languages.IPExpected); // } // Server.BanList.addException(playerName); // Tools.NotifyAllOps(playerName + Languages.Ban_Banned + " [" + sender.SenderName + "]", true); // if (!Server.BanList.Save()) // { // Tools.NotifyAllOps(Languages.Ban_FailedToSave + sender.SenderName + "'s " + Languages.Command, true); // } //} ///// <summary> ///// Removes an exception from the ban list. ///// </summary> ///// <param name="sender">Sending player</param> ///// <param name="args">Arguments sent with command</param> //public static void UnBan(ISender sender, ArgumentList args) //{ // string playerName; // if (!args.TryGetString(0, out playerName)) // { // throw new CommandError(Languages.IPExpected); // } // Server.BanList.removeException(playerName); // Tools.NotifyAllOps(playerName + Languages.Ban_UnBanned + " [" + sender.SenderName + "]", true); // if (!Server.BanList.Save()) // { // Tools.NotifyAllOps(Languages.Ban_FailedToSave + sender.SenderName + "'s " + Languages.Command, true); // } //} /// <summary> /// Sets the time in the game. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void Time(ISender sender, ArgumentList args) { double time; WorldTime text; if (args.TryParseOne<Double>("-set", out time) || args.TryParseOne<Double>("set", out time)) { if (time >= WorldTime.TimeMin && time <= WorldTime.TimeMax) { World.SetTime(time); } else { sender.SendMessage(String.Format("Invalid time specified, must be from {0} to {1}", WorldTime.TimeMin, WorldTime.TimeMax)); return; } } else if (args.TryParseOne<WorldTime>("-set", out text) || args.TryParseOne<WorldTime>("set", out text)) { time = text.GameTime; World.SetParsedTime(time); } else { string caseType = args.GetString(0); switch (caseType) { case "day": { World.SetTime(13500.0); break; } case "dawn": { World.SetTime(0); break; } case "dusk": { World.SetTime(0, false); break; } case "noon": { World.SetTime(27000.0); break; } case "night": { World.SetTime(16200.0, false); break; } case "?": case "now": case "-now": { sender.Message("Current time: " + WorldTime.Parse(World.GetParsableTime()).ToString()); return; } default: { sender.Message("Please review your command"); return; } } } NetMessage.SendData((int)Packet.WORLD_DATA); //Update Data var current = WorldTime.Parse(World.GetParsableTime()).Value; Tools.NotifyAllPlayers(String.Format("Time set to {0} ({1}) by {2}", current.ToString(), current.GameTime, sender.SenderName), Color.Green); }
/// <summary> /// Shows the help. /// </summary> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public static void ShowHelp(ISender sender, ArgumentList args) { var commands = sender.GetAvailableCommands(); if (commands != null && commands.Count > 0) { int page = 0; if (!args.TryGetInt(0, out page)) { if (args.Count > 0) { var command = args.GetString(0); if (commands.ContainsKey(command)) { sender.SendMessage(commands[command].description); commands[command].ShowHelp(sender, true); return; } else throw new CommandError("No such command: " + command); } } else page--; // const Int32 MaxLines = 5; var maxLines = sender is Player ? 5 : 15; var lineOffset = page * maxLines; var maxPages = (int)Math.Ceiling(commands.Count / (double)maxLines); if (page >= 0 && page < maxPages) { var cmds = new List<CommandInfo>(); var sorted = commands .OrderBy(x => x.Key.ToLower()) .Select(x => x.Value) .ToArray(); for (var i = lineOffset; i < lineOffset + maxLines; i++) { if (i < sorted.Length) cmds.Add(sorted[i]); } var prefixMax = cmds .Select(x => x.Prefix.Length) .OrderByDescending(x => x) .First(); foreach (var cmd in cmds) cmd.ShowDescription(sender, prefixMax); sender.SendMessage(String.Format("[Page {0} / {1}]", page + 1, maxPages)); } else { sender.SendMessage("Usage:"); sender.SendMessage(" help <command> - Get help for a command."); sender.SendMessage(" help <page> - View a list of commands. Valid page numbers are 1 to " + maxPages + "."); sender.SendMessage("Examples:"); sender.SendMessage(" help oplogin"); sender.SendMessage(" help 1"); } } else sender.SendMessage("You have no available commands."); }
///// <summary> ///// Allows a user to take backups and purge old data ///// </summary> ///// <param name="sender"></param> ///// <param name="args"></param> //public static void Backups(ISender sender, ArgumentList args) //{ // var perform = args.TryPop("now"); // var purge = args.TryPop("purge"); // if (perform) // BackupManager.PerformBackup(); // else if (purge) // { // int minutes; // if (args.TryParseOne<Int32>(out minutes)) // { // var backups = BackupManager.GetBackupsBefore(Main.worldName, DateTime.Now.AddMinutes(-minutes)); // var failCount = 0; // foreach (var backup in backups) // try // { // File.Delete(backup); // } // catch { failCount++; } // if (failCount > 0) // sender.Message( // String.Format("Failed to deleted {0} backup(s).", failCount) // ); // else // sender.Message( // String.Format("Deleted {0} backup(s).", backups.Length - failCount) // ); // } // else // throw new CommandError("Please specify a time frame."); // } // else // throw new CommandError("Argument expected."); //} /// <summary> /// Allows an OP to force the time to dtay at a certain point. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public void Timelock(ISender sender, ArgumentList args) { var disable = args.TryPop("disable"); var setNow = args.TryPop("now"); var setMode = args.TryPop("set"); var setAt = args.TryPop("setat"); if (disable) { if (!(args.Plugin as Entry).UseTimeLock) { sender.Message("Time lock is already disabled", 255, 255, 0, 0); return; } (args.Plugin as Entry).UseTimeLock = false; sender.Message("Time lock has been disabled.", 255, 0, 255, 0); return; } else if (setNow) (args.Plugin as Entry).UseTimeLock = true; else if (setMode) { string caseType = args.GetString(0); switch (caseType) { case "day": { World.SetTime(13500.0); break; } case "dawn": { World.SetTime(0); break; } case "dusk": { World.SetTime(0, false); break; } case "noon": { World.SetTime(27000.0); break; } case "night": { World.SetTime(16200.0, false); break; } default: { sender.Message("Please review your command.", 255, 255, 0, 0); return; } } (args.Plugin as Entry).UseTimeLock = true; } else if (setAt) { double time; if (args.TryParseOne<Double>(out time)) { this.TimelockTime = time; this.TimelockRain = Main.raining; this.TimelockSlimeRain = Main.slimeRain; this.UseTimeLock = true; } else throw new CommandError("Double expected."); } else throw new CommandError("Certain arguments expected."); if ((args.Plugin as Entry).UseTimeLock) { //if (!setNow) NewNetMessage.SendData(Packet.WORLD_DATA); if (!setNow) NetMessage.SendData((int)Packet.WORLD_DATA); sender.Message( String.Format("Time lock has set at {0}.", (args.Plugin as Entry).TimelockTime), 255, 0, 255, 0 ); } }
/// <summary> /// De-OPs a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void DeopPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); if (Storage.IsAvailable) { var existing = Authentication.GetPlayer(playerName); if (existing != null) { if (!existing.Operator) { throw new CommandError("Player is not an operator"); } var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("Your server operator privledges have been revoked.", Color.DarkRed); player.SetOp(false); player.SetAuthentication(null, "tdsm"); } if (Authentication.UpdatePlayer(playerName, null, false)) { sender.Message("Deop success", Color.DarkGreen); } else { sender.Message("Failed to deop player", Color.DarkRed); } } else { sender.SendMessage("No user found by " + playerName); } } else { if (Core.Ops.Contains(playerName)) { var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("Your server operator privledges have been revoked.", Color.Green); player.SetOp(false); player.SetAuthentication(null, "tdsm"); } Utils.NotifyAllOps("De-Opping " + playerName + " [" + sender.SenderName + "]", true); Core.Ops.Remove(playerName, true); if (!Core.Ops.Save()) { Utils.NotifyAllOps("Failed to save op list [" + sender.SenderName + "]", true); } } else { sender.SendMessage("No user found by " + playerName); } } }
/// <summary> /// Allows on the fly variable modifications /// </summary> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> public void VariableMan(ISender sender, ArgumentList args) { // var <exec|field> // var field <namespace.type> <fieldname> // var field <namespace.type> <fieldname> <valuetobeset> // var exec <namespace.type> <methodname> //No arguments supported yet var cmd = args.GetString(0); if (cmd == "field") { var type = args.GetString(1); var mem = args.GetString(2); //Find the type var at = Type.GetType(type); if (at == null) at = System.Reflection.Assembly.GetEntryAssembly().GetType(type); if (at == null) at = System.Reflection.Assembly.GetCallingAssembly().GetType(type); if (at == null) at = System.Reflection.Assembly.GetExecutingAssembly().GetType(type); if (at == null) throw new CommandError("Invalid type: " + type); //Find the field var am = at.GetField(mem); if (am == null) throw new CommandError("Invalid field: " + mem); string val = null; if (args.TryGetString(3, out val)) { object data = GetDataValue(am.FieldType, val); am.SetValue(null, data); var v = am.GetValue(null); if (v != null) val = v.ToString(); else val = "null"; sender.Message("Value is now: " + val); } else { var v = am.GetValue(null); if (v != null) val = v.ToString(); else val = "null"; sender.Message("Value: " + val); } } else if (cmd == "prop") { var type = args.GetString(1); var prop = args.GetString(2); //Find the type var at = Type.GetType(type); if (at == null) at = System.Reflection.Assembly.GetEntryAssembly().GetType(type); if (at == null) at = System.Reflection.Assembly.GetCallingAssembly().GetType(type); if (at == null) at = System.Reflection.Assembly.GetExecutingAssembly().GetType(type); if (at == null) throw new CommandError("Invalid type: " + type); //Find the field var am = at.GetProperty(prop); if (am == null) throw new CommandError("Invalid property: " + prop); string val = null; if (args.TryGetString(3, out val)) { object data = GetDataValue(am.PropertyType, val); am.SetValue(null, data, null); var v = am.GetValue(null, null); if (v != null) val = v.ToString(); else val = "null"; sender.Message("Value is now: " + val); } else { var v = am.GetValue(null, null); if (v != null) val = v.ToString(); else val = "null"; sender.Message("Value: " + val); } } else if (cmd == "exec") { var type = args.GetString(1); var mthd = args.GetString(2); //Find the type var at = Type.GetType(type); if (at == null) at = System.Reflection.Assembly.GetEntryAssembly().GetType(type); if (at == null) at = System.Reflection.Assembly.GetCallingAssembly().GetType(type); if (at == null) at = System.Reflection.Assembly.GetExecutingAssembly().GetType(type); if (at == null) throw new CommandError("Invalid type: " + type); //Find the field var am = at.GetMethod(mthd); if (am == null) throw new CommandError("Invalid method: " + mthd); var prms = am.GetParameters(); if (prms.Length == 0) { var res = am.Invoke(null, null); var result = res == null ? "null" : res.ToString(); sender.Message("Result: " + result); } else sender.Message("Arguments are not yet supported for exec"); } else sender.Message("Unsupported var command: " + cmd); }
public void Invasion(ISender sender, ArgumentList args) { if (Main.invasionType == 0) { var custom = args.TryPop("-custom"); if (custom) { if (args.Count > 0) { var npcIds = new List <Int32>(); while (args.Count > 0) { int npcType; string npc; if (args.TryGetInt(0, out npcType)) { npcIds.Add(npcType); } else if (args.TryGetString(0, out npc)) { var match = Definitions.DefinitionManager.FindNPC(npc); if (match.Length == 1) { npcIds.Add(match[0].Id); } else if (match.Length == 0) { sender.Message("Cannot find a NPC by `{0}`", npc); return; } else { sender.Message("Found too many NPC's containing `{0}`", npc); return; } } else { throw new CommandError("Expected a NPC id or name."); } } //Schedule... //if (!_customInvasion.IsEmpty()) _customInvasion.Enabled = false; //_customInvasion = new Task() //{ // Trigger = 10, // Data = npcIds, // Method = (task) => // { // var ids = task.Data as List<Int32>; // for (var x = 0; x < 5; x++) // { // var ix = Main.rand.Next(0, ids.Count - 1); // var pos = FindPositionOutOfSight(); // if (pos.HasValue) // { // } // } // } //}; if (_invasion != null) { lock (_invasion) _invasion = npcIds; } else { _invasion = npcIds; } Main.StartInvasion(_assignedInvasionType); } else { throw new CommandError("Expected npc type or name"); } } else { var txt = args.GetString(0).ToLower(); var vals = Enum.GetValues(typeof(InvasionType)); foreach (InvasionType it in vals) { if (it.ToString().ToLower() == txt) { Main.StartInvasion((int)it); sender.Message("A {0} invasion has begun.", it); return; } } sender.Message("No such invasion of type {0}", txt); } } else { if (args.TryPop("end") || args.TryPop("stop") || args.TryPop("cancel")) { //if (!_customInvasion.IsEmpty()) _customInvasion.Enabled = false; Main.invasionType = 0; if (_invasion != null) { lock (_invasion) _invasion.Clear(); } sender.Message("The invasion has now been stopped."); } else { sender.Message("An invasion is already under way."); } } }
/// <summary> /// De-OPs a given Player. /// </summary> /// <param name="sender">Sending player</param> /// <param name="args">Arguments sent with command</param> public void DeopPlayer(ISender sender, ArgumentList args) { var playerName = args.GetString(0); //Player player; //if (args.TryGetOnlinePlayer(0, out player)) //{ // playerName = player.Name; // if (Server.Ops.Contains(playerName, true)) // { // player.SendMessage("Your OP privledges have been revoked.", Color.Green); // } // player.Op = false; //} if (Ops.Contains(playerName)) { var player = Tools.GetPlayerByName(playerName); if (player != null) { player.SendMessage("Your server operator privledges have been revoked.", Color.Green); player.Op = false; } Tools.NotifyAllOps("De-Opping " + playerName + " [" + sender.SenderName + "]", true); Ops.Remove(playerName, true); if (!Ops.Save()) { Tools.NotifyAllOps("Failed to save op list [" + sender.SenderName + "]", true); } } else sender.SendMessage("No user found by " + playerName); }
void GroupPermission(ISender sender, ArgumentList args) { if (!Storage.IsAvailable) throw new CommandError("No permissions plugin or data plugin is attached"); int a = 0; string groupName; bool applyToGuests; string parent, prefix, suffix; byte r = 0, g = 0, b = 0; var cmd = args.GetString(a++); switch (cmd) { case "add": //group add "Guest" <ApplyToGuests> <Parent> <R> <G> <B> <Prefix> <Suffix> if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after [" + cmd + "]"); args.TryGetBool(a++, out applyToGuests); args.TryGetString(a++, out parent); if (!args.TryGetByte(a++, out r)) r = 255; if (!args.TryGetByte(a++, out g)) g = 255; if (!args.TryGetByte(a++, out b)) b = 255; args.TryGetString(a++, out prefix); args.TryGetString(a++, out suffix); if (Storage.FindGroup(groupName) != null) throw new CommandError("There is already a group defined as " + groupName); if (Storage.AddOrUpdateGroup(groupName, applyToGuests, parent, r, g, b, prefix, suffix) != null) { sender.Message("Successfully created group " + groupName, Color.Green); } else { sender.Message("Failed to create group " + groupName, Color.Red); } break; case "remove": //group remove "Guest if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after [" + cmd + "]"); if (Storage.FindGroup(groupName) == null) throw new CommandError("Group does not exist: " + groupName); if (Storage.RemoveGroup(groupName)) { sender.Message("Successfully removed group " + groupName, Color.Green); } else { sender.Message("Failed to remove group " + groupName, Color.Red); } break; case "update": //group update "Guest" <ApplyToGuests> <Parent> <R> <G> <B> <Prefix> <Suffix> if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after [" + cmd + "]"); args.TryGetBool(a++, out applyToGuests); args.TryGetString(a++, out parent); if (!args.TryGetByte(a++, out r)) r = 255; if (!args.TryGetByte(a++, out g)) g = 255; if (!args.TryGetByte(a++, out b)) b = 255; args.TryGetString(a++, out prefix); args.TryGetString(a++, out suffix); if (Storage.FindGroup(groupName) == null) throw new CommandError("This is no group defined as " + groupName); if (Storage.AddOrUpdateGroup(groupName, applyToGuests, parent, r, g, b, prefix, suffix) != null) { sender.Message("Successfully updated group " + groupName, Color.Green); } else { sender.Message("Failed to update group " + groupName, Color.Red); } break; case "addnode": //group addnode "Guest" "tdsm.help" <deny> if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after [" + cmd + "]"); string addNode; if (!args.TryGetString(a++, out addNode)) throw new CommandError("Expected node name after group name"); bool deny; if (!args.TryGetBool(a++, out deny)) deny = false; if (Storage.FindGroup(groupName) == null) throw new CommandError("Group does not exist: " + groupName); if (Storage.AddGroupNode(groupName, addNode, deny ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully added node {0} to group {1} ", addNode, groupName), Color.Green); } else { sender.Message(String.Format("Failed to add node {0} to group {1} ", addNode, groupName), Color.Red); } break; case "removenode": //group removenode "Guest" "tdsm.help" if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after [" + cmd + "]"); string remNode; if (!args.TryGetString(a++, out remNode)) throw new CommandError("Expected node name after group name"); if (Storage.FindGroup(groupName) == null) throw new CommandError("Group does not exist: " + groupName); bool denied; if (!args.TryGetBool(a++, out denied)) denied = false; if (Storage.RemoveGroupNode(groupName, remNode, denied ? Permission.Denied : Permission.Permitted)) { sender.Message(String.Format("Successfully removed node {0} from group {1} ", remNode, groupName), Color.Green); } else { sender.Message(String.Format("Failed to remove node {0} from group {1} ", remNode, groupName), Color.Red); } break; case "list": //group list var groups = Storage.GroupList(); if (groups != null && groups.Length > 0) { sender.Message("Current groups:"); foreach (var grp in groups) { sender.Message("\t" + grp); } } else { sender.Message("There are no registered groups."); } break; case "listnodes": //group listnodes "Guest" //Could be used in 'list' but this will make things a bit more simple for the end user. if (!args.TryGetString(a++, out groupName)) throw new CommandError("Expected group name after [" + cmd + "]"); var grpList = Storage.FindGroup(groupName); if (grpList == null) throw new CommandError("Group does not exist: " + groupName); var nodes = Storage.GroupNodes(groupName); if (nodes != null && nodes.Length > 0) { sender.Message("Current permissions for group {0}:", grpList.Name); foreach (var nd in nodes) { sender.Message("\t{0}\t- {1}", (nd.Permission == Permission.Denied) ? "Denied" : "Allowed", nd.Node); } } else { sender.Message("There are no permissions assigned to group: " + grpList.Name); } break; default: throw new CommandError("Invalid command " + cmd); } }
internal static void RConCommand(ISender sender, ArgumentList args) { string name; if (args.TryParseOne("cut", out name)) { if (sender is Player || sender is RConSender) { sender.sendMessage("You cannot perform that action.", 255, 238, 130, 238); return; } var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) { rcon.Close(); } } ProgramLog.Admin.Log("Cut all remote console connections from {0}.", name); } else if (args.TryParseOne("ban", out name)) { if (sender is Player || sender is RConSender) { sender.sendMessage("You cannot perform that action.", 255, 238, 130, 238); return; } LoginDatabase.setValue(name, null); var lower = name.ToLower(); foreach (var rcon in clients) { if (rcon.Name.ToLower() == lower) { rcon.Close(); } } ProgramLog.Admin.Log("Cut all remote console connections from {0} and revoked credentials.", name); } else if (args.Count == 1 && args.GetString(0) == "list") { foreach (var rcon in clients) { sender.sendMessage(String.Format("{0} {1}", rcon.Id, rcon.state)); } } else if (args.Count == 1 && args.GetString(0) == "load") { if (sender is Player || sender is RConSender) { sender.sendMessage("You cannot perform that action.", 255, 238, 130, 238); return; } LoginDatabase.Load(); ProgramLog.Admin.Log("Reloaded remote console login database."); } else { throw new CommandError(""); } }