Beispiel #1
0
        public bool ChangeGroup(object Player, object Group)
        {
            TShockAPI.TSPlayer p = null;
            TShockAPI.DB.User  u = new TShockAPI.DB.User();
            string             g = "";

            if ((p = GetPlayer(Player)) == null)
            {
                return(false);
            }

            if (Group is string)
            {
                g = Group as string;
            }
            else if (Group is TShockAPI.Group)
            {
                g = (Group as TShockAPI.Group).Name;
            }

            if (string.IsNullOrEmpty(g) == true)
            {
                return(false);
            }

            try {
                u.Name = p.User.Name;
                TShockAPI.TShock.Users.SetUserGroup(u, g);
            } catch (Exception ex) {
                ScriptLog.ErrorFormat("tshock_change_group", "Group change failed: {0}", ex.Message);
                return(false);
            }

            return(true);
        }
Beispiel #2
0
		public static void OnAccountDelete(User u)
		{
			if (AccountDelete == null)
				return;

			AccountDelete(new AccountDeleteEventArgs(u));
		}
		public async Task<bool> AddAsync(User user, DateTime expiration)
		{
			return await Task.Run(() =>
			{
				syncLock.EnterWriteLock();

				try
				{
					return db.Query("INSERT INTO Mutes VALUES (@0, @1, @2, @3, @4, @5)",
						null,
						user.Name,
						user.UUID,
						JsonConvert.DeserializeObject<List<string>>(user.KnownIps)[0],
						DateTime.UtcNow.ToString("s"),
						expiration.ToString("s")) > 0;
				}
				catch (Exception ex)
				{
					TShock.Log.Error(ex.ToString());
					return false;
				}
				finally
				{
					syncLock.ExitWriteLock();
				}
			});
		}
        private object BanList(RestRequestArgs args)
        {
            var banList = new ArrayList();

            foreach (var ban in TShock.Bans.GetBans())
            {
                int userId = -1;
                try
                {
                    TShockAPI.DB.User user = TShock.Users.GetUserByName(ban.Name);
                    userId = user.ID;
                }
                catch (NullReferenceException e) {
                    userId = -1;
                }
                banList.Add(
                    new Dictionary <string, string>
                {
                    { "name", null == ban.Name ? "" : ban.Name },
                    { "userid", String.Format("{0}", userId) },
                    { "ip", null == ban.IP ? "" : ban.IP },
                    { "reason", null == ban.Reason ? "" : ban.Reason },
                    { "banninguser", null == ban.BanningUser? "" : ban.BanningUser },
                    { "date", null == ban.Date ? "" : ban.Date },
                    { "expiration", null == ban.Expiration ? "" : ban.Expiration },
                }
                    );
            }

            return(new RestObject()
            {
                { "bans", banList }
            });
        }
Beispiel #5
0
        public bool ChangeGroup(object Player, object Group)
        {
            TShockAPI.TSPlayer p = null;
            TShockAPI.DB.User u = new TShockAPI.DB.User();
            string g = "";

            if ((p = GetPlayer(Player)) == null) {
                return false;
            }

            if (Group is string) {
                g = Group as string;
            } else if (Group is TShockAPI.Group) {
                g = (Group as TShockAPI.Group).Name;
            }

            if (string.IsNullOrEmpty(g) == true) {
                return false;
            }

            try {
                u.Name = p.User.Name;
                TShockAPI.TShock.Users.SetUserGroup(u, g);
            } catch (Exception ex) {
                ScriptLog.ErrorFormat("tshock_change_group", "Group change failed: {0}", ex.Message);
                return false;
            }

            return true;
        }
Beispiel #6
0
        private void displayStats(TSPlayer who, TShockAPI.DB.User user)
        {
            string query       = "SELECT * FROM Uno WHERE UserID = " + user.ID.ToString();
            int    totalgames  = -1;
            int    totalwins   = -1;
            int    totalpoints = -1;

            using (QueryResult reader = db.QueryReader(query))
            {
                while (reader.Read())
                {
                    totalgames  = reader.Get <int>("TotalGames");
                    totalwins   = reader.Get <int>("TotalWins");
                    totalpoints = reader.Get <int>("TotalPoints");
                }
            }
            if (totalgames == -1)
            {
                who.SendErrorMessage("No Uno stats to display.");
            }
            else
            {
                who.SendInfoMessage("{0} has won {1} game(s) out of {2} with a point total of {3}.", user.Name, totalwins.ToString(), totalgames.ToString(), totalpoints.ToString());
            }
        }
        public static void SendEmail(TSPlayer player, string email, User user)
        {
            MailMessage mail = new MailMessage(AccountRecovery.Config.EmailFrom, email);
            SmtpClient client = new SmtpClient();
            client.Timeout = 15000;
            client.Host = AccountRecovery.Config.HostSMTPServer;
            client.Port = AccountRecovery.Config.HostPort;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.UseDefaultCredentials = false;
            client.Credentials = new System.Net.NetworkCredential(AccountRecovery.Config.ServerEmailAddress, AccountRecovery.Config.ServerEmailPassword);
            client.EnableSsl = true;
            //client.ServicePoint.MaxIdleTime = 1;
            mail.Subject = AccountRecovery.Config.EmailSubjectLine;
            mail.Body = AccountRecovery.Config.EmailBodyLine;
            mail.IsBodyHtml = AccountRecovery.Config.UseHTML;

            string passwordGenerated = GeneratePassword(AccountRecovery.Config.GeneratedPasswordLength);
            TShock.Users.SetUserPassword(user, passwordGenerated);
            TShock.Log.ConsoleInfo("{0} has requested a new password succesfully.", user.Name);

            mail.Body = string.Format(mail.Body.Replace("$NEW_PASSWORD", passwordGenerated));
            mail.Body = string.Format(mail.Body.Replace("$USERNAME", user.Name));

            client.Send(mail);
            client.Dispose();
            player.SendSuccessMessage("A new password has been generated and sent to {0} for {1}.", email, user.Name);
            TShock.Log.ConsoleInfo("A new password has been generated and sent to {0} for {1}.", email, user.Name);
        }
        public static RestObject updateInventory(RestRequestArgs args)
        {
            if (string.IsNullOrWhiteSpace(args.Parameters["account"]))
            {
                return new RestObject("400")
                       {
                           Response = "Invalid account."
                       }
            }
            ;
            int userId = Convert.ToInt32(args.Parameters["account"]);

            if (userId <= 0)
            {
                return(new RestObject("400")
                {
                    Response = "Invalid account."
                });
            }

            if (string.IsNullOrWhiteSpace(args.Parameters["inventory"]))
            {
                return(RestMissingParam("inventory"));
            }
            string inventory = Convert.ToString(args.Parameters["inventory"]);

            if (inventory == null)
            {
                return(new RestObject("400")
                {
                    Response = "Invalid inventory."
                });
            }

            TShockAPI.DB.User user = TShock.Users.GetUserByID(userId);
            foreach (var player in TShock.Players.Where(p => null != p && p.UserAccountName == user.Name))
            {
                return(new RestObject("400")
                {
                    Response = "Player active, inventory may not be changed."
                });
            }

            bool ok = ModifySSCInventory(userId, inventory);

            if (ok)
            {
                return new RestObject {
                           { "update", inventory }
                }
            }
            ;
            else
            {
                return new RestObject("400")
                       {
                           Response = "Update failure."
                       }
            };
        }
Beispiel #9
0
        private void UnoStats(CommandArgs args)
        {
            if (args.Parameters.Count == 0)
            {
                TShockAPI.DB.User user = TShock.Users.GetUserByName(args.Player.User.Name);
                displayStats(args.Player, user);
            }
            else if (args.Parameters.Count == 1 && args.Parameters[0] == "all")
            {
                List <UPlayer> unsorted = new List <UPlayer>();
                using (QueryResult reader = db.QueryReader("SELECT * FROM Uno"))
                {
                    while (reader.Read())
                    {
                        unsorted.Add(new UPlayer()
                        {
                            _totalgames = reader.Get <int>("TotalGames"), _totalpoints = reader.Get <int>("TotalPoints"), _totalwins = reader.Get <int>("TotalWins"), _userid = reader.Get <int>("UserID"), _winpercent = ((double)reader.Get <int>("TotalWins") / (double)reader.Get <int>("TotalGames") * 100)
                        });
                    }
                }

                unsorted.OrderBy(p => p._winpercent);
                unsorted.Reverse();

                args.Player.SendInfoMessage("[Uno] Top three UnoStats players with more than 5 games:");

                int displayed = 0;
                for (int i = 0; i < unsorted.Count; i++)
                {
                    if (unsorted[i]._totalwins <= 5)
                    {
                        continue;
                    }
                    displayed++;

                    string winpercentage = unsorted[i]._winpercent.ToString();
                    if (winpercentage.Length > 6)
                    {
                        winpercentage = winpercentage.Remove(6);
                    }

                    args.Player.SendInfoMessage("[Uno] {0} has won {1} games out of {2} ({3}%), with a point total of {4}.", TShock.Users.GetUserByID(unsorted[i]._userid).Name, unsorted[i]._totalwins.ToString(), unsorted[i]._totalgames.ToString(), winpercentage, unsorted[i]._totalpoints.ToString());
                }
            }
            else
            {
                string            para = string.Join(" ", args.Parameters.Select(p => p));
                TShockAPI.DB.User user = TShock.Users.GetUserByName(para);
                if (user != null)
                {
                    displayStats(args.Player, user);
                }
                else
                {
                    args.Player.SendErrorMessage("Unknown Player!");
                }
            }
        }
Beispiel #10
0
 public static bool InsertTradeLog(User trader, User tradee, string traderItems, string tradeeItems, DateTime tradeDate)
 {
     try
     {
         return TShock.CharacterDB.database.Query("INSERT INTO TradeRequestLogs (Trader, Tradee, TraderItems, TradeeItems, TradeDate) VALUES (@0, @1, @2, @3, @4);", trader.Name, tradee.Name, traderItems, tradeeItems, tradeDate.ToString("s")) != 0;
     }
     catch (Exception ex)
     {
         TShock.Log.Error(ex.ToString());
     }
     return false;
 }
        private void RemoteClient_PacketReceived(Client sender, Client.PacketReceivedEventArgs e)
        {
            PacketType packetType = (PacketType)e.Reader.ReadInt16();

            //Disconnect the user if he attempts to do anything else before authenticating.
            if (packetType != PacketType.Authenticate && !Authenticated)
            {
                Disconnect("Your attempt at sending packets before authenticating has been ignored!");
                return;
            }
            switch (packetType)
            {
                case PacketType.Authenticate:
                    InterfaceType = (InterfaceType)e.Reader.ReadByte();
                    int major = e.Reader.ReadInt32();
                    int minor = e.Reader.ReadInt32();
                    if (Rtc.buildVersion.Major != major || Rtc.buildVersion.Minor != minor)
                    {
                        Disconnect($"Your version ({major}.{minor}) is incompatible with the server's version ({Rtc.buildVersion.Major}.{Rtc.buildVersion.Minor}).");
                        return;
                    }
                    string Username = e.Reader.ReadString();
                    string Password = e.Reader.ReadString();
                    TSUser = TShock.Users.GetUserByName(Username);

                    if (TSUser == null || !TSUser.VerifyPassword(Password))
                    {
                        Disconnect("Invalid username/password or insufficient privileges.");
                        return;
                    }
                    Group g = TShock.Groups.GetGroupByName(TSUser.Group);

                    if (!g.HasPermission("*"))
                    {
                        Disconnect("Invalid username/password or insufficient privileges.");
                        return;
                    }
                    Authenticated = true;
                    Packet pck = new Packet((short)PacketType.MessageBuffer, (short)Rtc.MessagesBuffer.Length);
                    for (int i = 0; i < Rtc.MessagesBuffer.Length; i++)
                    {
                        if (!string.IsNullOrEmpty(Rtc.MessagesBuffer[i]))
                           pck.Write(Rtc.ColorBuffer[i], Rtc.MessagesBuffer[i]);

                    }
                    sender.Send(pck);
                    break;
                case PacketType.Input:
                    string text = e.Reader.ReadString();
                    Rtc.ConsoleInput.SendText(text);
                    break;
            }
        }
Beispiel #12
0
        public static IList<string> GetUserTradeLogs(User user, bool recent)
        {
            try
            {
				if(recent)
				{
					using (var reader = TShock.DB.QueryReader("SELECT * FROM TradeRequestLogs ORDER BY TradeRequestLogs.TradeDate DESC LIMIT 20"))
					{
						IList<string> results = new List<string>();
						while (reader.Read())
						{
							string trader = reader.Get<String>("Trader");
							string tradee = reader.Get<String>("Tradee");
							string traderItems = reader.Get<String>("TraderItems");
							string tradeeItems = reader.Get<String>("TradeeItems");
							string tradeDate = reader.Get<String>("TradeDate");

							results.Add(string.Format("{0} - {1} {2} <-> {3} {4}", DateTime.Parse(tradeDate), trader, traderItems, tradeeItems, tradee));
						}
						return results;
					}
				}
				else
				{
					// using (var reader = TShock.DB.QueryReader("SELECT * FROM TradeRequestLogs WHERE Trader LIKE '%@0%' OR Tradee LIKE '%@1%'", user.Name, user.Name))
					using (var reader = TShock.DB.QueryReader("SELECT * FROM TradeRequestLogs WHERE Trader=@0 OR Tradee=@1", user.Name, user.Name))
					{
						IList<string> results = new List<string>();
						while (reader.Read())
						{
							string trader = reader.Get<String>("Trader");
							string tradee = reader.Get<String>("Tradee");
							string traderItems = reader.Get<String>("TraderItems");
							string tradeeItems = reader.Get<String>("TradeeItems");
							string tradeDate = reader.Get<String>("TradeDate");

							results.Add(string.Format("{0} - {1} {2} <-> {3} {4}", DateTime.Parse(tradeDate), trader, traderItems, tradeeItems, tradee));
						}
						return results;
					}
				}
            }
            catch (Exception ex)
            {
                TShock.Log.ConsoleError("FetchHashedPasswordAndGroup SQL returned an error: " + ex);
            }
            return null;
        }
Beispiel #13
0
		/// <summary>
		/// Adds a given username to the database
		/// </summary>
		/// <param name="user">User user</param>
		public void AddUser(User user)
		{
			if (!TShock.Groups.GroupExists(user.Group))
				throw new GroupNotExistsException(user.Group);

			int ret;
			try
			{
				ret = _database.Query("INSERT INTO Users (Username, Password, UUID, UserGroup, Registered) VALUES (@0, @1, @2, @3, @4);", user.Name,
					user.Password, user.UUID, user.Group, DateTime.UtcNow.ToString("s"));
			}
			catch (Exception ex)
			{
				// Detect duplicate user using a regexp as Sqlite doesn't have well structured exceptions
				if (Regex.IsMatch(ex.Message, "Username.*not unique"))
					throw new UserExistsException(user.Name);
				throw new UserManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex);
			}

			if (1 > ret)
				throw new UserExistsException(user.Name);

			Hooks.AccountHooks.OnAccountCreate(user);
		}
Beispiel #14
0
        /// <summary>
        /// Sets the group for a given username
        /// </summary>
        /// <param name="user">User user</param>
        /// <param name="group">string group</param>
        public void SetUserGroup(User user, string group)
        {
            try
            {
                Group grp = TShock.Groups.GetGroupByName(group);
                if (null == grp)
                    throw new GroupNotExistsException(group);

                if (database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, user.Name) == 0)
                    throw new UserNotExistException(user.Name);

                // Update player group reference for any logged in player
                foreach (var player in TShock.Players.Where(p => null != p && p.UserAccountName == user.Name))
                {
                    player.Group = grp;
                }
            }
            catch (Exception ex)
            {
                throw new UserManagerException("SetUserGroup SQL returned an error", ex);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Removes a given username from the database
        /// </summary>
        /// <param name="user">User user</param>
        public void RemoveUser(User user)
        {
            try
            {
                int affected = database.Query("DELETE FROM Users WHERE Username=@0", user.Name);

                if (affected < 1)
                    throw new UserNotExistException(user.Name);
            }
            catch (Exception ex)
            {
                throw new UserManagerException("RemoveUser SQL returned an error", ex);
            }
        }
Beispiel #16
0
        public User GetUser(User user)
        {
            bool multiple = false;
            string query;
            string type;
            object arg;
            if (0 != user.ID)
            {
                query = "SELECT * FROM Users WHERE ID=@0";
                arg = user.ID;
                type = "id";
            }
            else
            {
                query = "SELECT * FROM Users WHERE Username=@0";
                arg = user.Name;
                type = "name";
            }

            try
            {
                using (var result = database.QueryReader(query, arg))
                {
                    if (result.Read())
                    {
                        user = LoadUserFromResult(user, result);
                        // Check for multiple matches
                        if (!result.Read())
                            return user;
                        multiple = true;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new UserManagerException("GetUser SQL returned an error (" + ex.Message + ")", ex);
            }
            if (multiple)
                throw new UserManagerException(String.Format("Multiple users found for {0} '{1}'", type, arg));

            throw new UserNotExistException(user.Name);
        }
Beispiel #17
0
        /// <summary>
        /// Adds a given username to the database
        /// </summary>
        /// <param name="user">User user</param>
        public void AddUser(User user)
        {
            if (!TShock.Groups.GroupExists(user.Group))
                throw new GroupNotExistsException(user.Group);

            int ret;
            try
            {
                ret = database.Query("INSERT INTO Users (Username, Password, UserGroup) VALUES (@0, @1, @2);", user.Name,
                                   TShock.Utils.HashPassword(user.Password), user.Group);
            }
            catch (Exception ex)
            {
                // Detect duplicate user using a regexp as Sqlite doesn't have well structured exceptions
                if (Regex.IsMatch(ex.Message, "Username.*not unique"))
                    throw new UserExistsException(user.Name);
                throw new UserManagerException("AddUser SQL returned an error (" + ex.Message + ")", ex);
            }

            if (1 > ret)
                throw new UserExistsException(user.Name);
        }
Beispiel #18
0
        private static void RegisterUser(CommandArgs args)
        {
            try
            {
                var user = new User();
                string echoPassword = "";
                if (args.Parameters.Count == 1)
                {
                    user.Name = args.Player.Name;
                    echoPassword = args.Parameters[0];
                    try
                    {
                        user.CreateBCryptHash(args.Parameters[0]);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
                        return;
                    }
                }
                else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
                {
                    user.Name = args.Parameters[0];
                    echoPassword = args.Parameters[1];
                    try
                    {
                        user.CreateBCryptHash(args.Parameters[1]);
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
                        return;
                    }
                }
                else
                {
                    args.Player.SendErrorMessage("Invalid syntax! Proper syntax: {0}register <password>", Specifier);
                    return;
                }

                user.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB. --Why?
                user.UUID = args.Player.UUID;

                if (TShock.Users.GetUserByName(user.Name) == null && user.Name != TSServerPlayer.AccountName) // Cheap way of checking for existance of a user
                {
                    args.Player.SendSuccessMessage("Account \"{0}\" has been registered.", user.Name);
                    args.Player.SendSuccessMessage("Your password is {0}.", echoPassword);
                    TShock.Users.AddUser(user);
                    TShock.Log.ConsoleInfo("{0} registered an account: \"{1}\".", args.Player.Name, user.Name);
                }
                else
                {
                    args.Player.SendErrorMessage("Account " + user.Name + " has already been registered.");
                    TShock.Log.ConsoleInfo(args.Player.Name + " failed to register an existing account: " + user.Name);
                }
            }
            catch (UserManagerException ex)
            {
                args.Player.SendErrorMessage("Sorry, an error occured: " + ex.Message + ".");
                TShock.Log.ConsoleError("RegisterUser returned an error: " + ex);
            }
        }
Beispiel #19
0
 private User LoadUserFromResult(User user, QueryResult result)
 {
     user.ID = result.Get<int>("ID");
     user.Group = result.Get<string>("Usergroup");
     user.Password = result.Get<string>("Password");
     user.Name = result.Get<string>("Username");
     user.LastAccessed = result.Get<string>("LastAccessed");
     user.KnownIps = result.Get<string>("KnownIps");
     return user;
 }
Beispiel #20
0
        private void ULeave(CommandArgs args)
        {
            if (args.Parameters.Count > 2 && args.Parameters[0].ToLower() == "set")
            {
                TShockAPI.DB.User player = TShock.Users.GetUserByName(args.Parameters[1]);

                if (player == null)
                {
                    args.Player.SendErrorMessage("User doesn't exist: {0}", args.Parameters[1]);
                    return;
                }

                if (player.Name != args.Player.User.Name && !args.Player.Group.HasPermission("oa.mod"))
                {
                    args.Player.SendErrorMessage("You do not have permission to change other players' leaving announcement.");
                    return;
                }

                List <string> param = args.Parameters;

                param.RemoveAt(0); //Remove 'set'
                param.RemoveAt(0); //Remove player name

                string announcement = string.Join(" ", param.Select(p => p));

                foreach (string badword in config.badwords)
                {
                    if (announcement.Contains(badword) && !args.Player.Group.HasPermission("oa.mod"))
                    {
                        args.Player.SendErrorMessage("You may not use the phrase {0} in this leaving announcement!", badword);
                        return;
                    }
                }

                setAnnounce(false, player.ID, player.Name, announcement);
                args.Player.SendSuccessMessage("{0} leaving announcement has been set to:", (player.Name == args.Player.User.Name ? "Your" : (player.Name + "'s")));
                args.Player.SendMessage(string.Format("[{0}] {1}", player.Name, players[player.ID].leave), players[player.ID].leaveRGB);

                return;
            }

            if (args.Parameters.Count == 2 && args.Parameters[0].ToLower() == "read")
            {
                TShockAPI.DB.User player = TShock.Users.GetUserByName(args.Parameters[1]);

                if (player == null)
                {
                    args.Player.SendErrorMessage("User doesn't exist: {0}", args.Parameters[1]);
                    return;
                }

                if (player.Name != args.Player.User.Name && !args.Player.Group.HasPermission("oa.mod"))
                {
                    args.Player.SendErrorMessage("You cannot view others' leaving announcements!");
                    return;
                }

                if (!players.ContainsKey(player.ID) || players[player.ID].leave == null)
                {
                    args.Player.SendErrorMessage("This player doesn't have a leaving announcement!");
                    return;
                }

                args.Player.SendMessage(string.Format("[{0}] {1}", player.Name, players[player.ID].leave), players[player.ID].leaveRGB);
                return;
            }

            if (args.Parameters.Count == 2 && args.Parameters[0].ToLower() == "remove")
            {
                TShockAPI.DB.User player = TShock.Users.GetUserByName(args.Parameters[1]);

                if (player == null)
                {
                    args.Player.SendErrorMessage("User doesn't exist: {0}", args.Parameters[1]);
                    return;
                }

                if (player.Name != args.Player.User.Name && !args.Player.Group.HasPermission("oa.mod"))
                {
                    args.Player.SendErrorMessage("You do not have permission to remove other players' leaving announcement.");
                    return;
                }

                if (!players.ContainsKey(player.ID) || players[player.ID].leave == null)
                {
                    args.Player.SendErrorMessage("This player doesn't have a leaving announcement to remove!");
                    return;
                }

                removeAnnounce(false, player.ID);
                args.Player.SendSuccessMessage("{0} leaving announcement has been removed.", (player.Name == args.Player.User.Name ? "Your" : (player.Name + "'s")));

                return;
            }

            if (args.Parameters.Count > 2 && args.Parameters[0].ToLower() == "color")
            {
                if (!args.Player.Group.HasPermission("oa.mod"))
                {
                    args.Player.SendErrorMessage("You do not have permission to change leaving announcement colors.");
                    return;
                }

                TShockAPI.DB.User player = TShock.Users.GetUserByName(args.Parameters[1]);

                if (player == null)
                {
                    args.Player.SendErrorMessage("User doesn't exist: {0}", args.Parameters[1]);
                    return;
                }

                if (!players.ContainsKey(player.ID) || players[player.ID].greet == null)
                {
                    args.Player.SendErrorMessage("This player doesn't have a greeting announcement to modify the color of!");
                    return;
                }

                Color color;

                List <string> param = args.Parameters;

                param.RemoveAt(0); //Remove 'color'
                param.RemoveAt(0); //Remove player name

                if (!tryParseColor(param, out color))
                {
                    args.Player.SendErrorMessage("Invalid color syntax: {0}leave color <player> rrr,ggg,bbb OR {0}leave color <player> rrr ggg bbb", (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier));
                    return;
                }

                setColor(false, player.ID, color);
                args.Player.SendSuccessMessage("{0} leaving announcement has been set to:", (player.Name == args.Player.User.Name ? "Your" : (player.Name + "'s")));
                args.Player.SendMessage(string.Format("[{0}] {1}", player.Name, players[player.ID].leave), players[player.ID].leaveRGB);

                return;
            }

            args.Player.SendErrorMessage("Invalid syntax:");
            args.Player.SendErrorMessage("{0}leave set <player> <announcement>", (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier));
            args.Player.SendErrorMessage("{0}leave remove <player>", (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier));
            if (args.Player.Group.HasPermission("oa.mod"))
            {
                args.Player.SendErrorMessage("{0}leave color <player> <rgb>", (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier));
                args.Player.SendErrorMessage("{0}leave read <player>", (args.Silent ? TShock.Config.CommandSilentSpecifier : TShock.Config.CommandSpecifier));
            }
        }
Beispiel #21
0
        private static void RegisterUser(CommandArgs args)
        {
            try
            {
                var user = new User();

                if (args.Parameters.Count == 1)
                {
                    user.Name = args.Player.Name;
                    user.Password = args.Parameters[0];
                }
                else if (args.Parameters.Count == 2 && TShock.Config.AllowRegisterAnyUsername)
                {
                    user.Name = args.Parameters[0];
                    user.Password = args.Parameters[1];
                }
                else
                {
                    args.Player.SendMessage("Invalid syntax! Proper syntax: /register <password>", Color.Red);
                    return;
                }

                user.Group = TShock.Config.DefaultRegistrationGroupName; // FIXME -- we should get this from the DB.

                if (TShock.Users.GetUserByName(user.Name) == null) // Cheap way of checking for existance of a user
                {
                    args.Player.SendMessage("Account " + user.Name + " has been registered.", Color.Green);
                    args.Player.SendMessage("Your password is " + user.Password);
                    TShock.Users.AddUser(user);
                    Log.ConsoleInfo(args.Player.Name + " registered an Account: " + user.Name);
                }
                else
                {
                    args.Player.SendMessage("Account " + user.Name + " has already been registered.", Color.Green);
                    Log.ConsoleInfo(args.Player.Name + " failed to register an existing Account: " + user.Name);
                }
            }
            catch (UserManagerException ex)
            {
                args.Player.SendMessage("Sorry, an error occured: " + ex.Message, Color.Green);
                Log.ConsoleError("RegisterUser returned an error: " + ex);
            }
        }
Beispiel #22
0
 public AccountCreateEventArgs(User user)
 {
     this.User = user;
 }
		public async Task<bool> DeleteAsync(User user)
		{
			return await Task.Run(() =>
			{
				syncLock.EnterWriteLock();
				string query = db.GetSqlType() == SqlType.Mysql ?
					"DELETE FROM Mutes WHERE UUID = @0 OR IP = @1 ORDER BY ID DESC LIMIT 1" :
					"DELETE FROM Mutes WHERE ID IN (SELECT ID FROM Mutes WHERE UUID = @0 OR IP = @1 ORDER BY ID DESC LIMIT 1)";

				try
				{
					return db.Query(query, user.UUID, JsonConvert.DeserializeObject<List<string>>(user.KnownIps)[0]) > 0;
				}
				catch (Exception ex)
				{
					TShock.Log.Error(ex.ToString());
					return false;
				}
				finally
				{
					syncLock.ExitWriteLock();
				}
			});
		}
Beispiel #24
0
        /// <summary>
        /// Sets the group for a given username
        /// </summary>
        /// <param name="user">User user</param>
        /// <param name="group">string group</param>
        public void SetUserGroup(User user, string group)
        {
            try
            {
                if (!TShock.Groups.GroupExists(group))
                    throw new GroupNotExistsException(group);

                if (database.Query("UPDATE Users SET UserGroup = @0 WHERE Username = @1;", group, user.Name) == 0)
                    throw new UserNotExistException(user.Name);
            }
            catch (Exception ex)
            {
                throw new UserManagerException("SetUserGroup SQL returned an error", ex);
            }
        }
Beispiel #25
0
        /// <summary>
        /// Removes a given username from the database
        /// </summary>
        /// <param name="user">User user</param>
        public void RemoveUser(User user)
        {
            try
            {
                int affected = -1;
                if (!string.IsNullOrEmpty(user.Address))
                {
                    affected = database.Query("DELETE FROM Users WHERE IP=@0", user.Address);
                }
                else
                {
                    affected = database.Query("DELETE FROM Users WHERE Username=@0", user.Name);
                }

                if (affected < 1)
                    throw new UserNotExistException(string.IsNullOrEmpty(user.Address) ? user.Name : user.Address);
            }
            catch (Exception ex)
            {
                throw new UserManagerException("RemoveUser SQL returned an error", ex);
            }
        }
Beispiel #26
0
        public User GetUser(User user)
        {
            try
            {
                QueryResult result;
                if (string.IsNullOrEmpty(user.Address))
                {
                    result = database.QueryReader("SELECT * FROM Users WHERE Username=@0", user.Name);
                }
                else
                {
                    result = database.QueryReader("SELECT * FROM Users WHERE IP=@0", user.Address);
                }

                using (var reader = result)
                {
                    if (reader.Read())
                    {
                        user.ID = reader.Get<int>("ID");
                        user.Group = reader.Get<string>("Usergroup");
                        user.Password = reader.Get<string>("Password");
                        user.Name = reader.Get<string>("Username");
                        user.Address = reader.Get<string>("IP");
                        return user;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new UserManagerException("GetUserID SQL returned an error", ex);
            }
            throw new UserNotExistException(string.IsNullOrEmpty(user.Address) ? user.Name : user.Address);
        }
Beispiel #27
0
 /// <summary>
 /// Sets the Hashed Password for a given username
 /// </summary>
 /// <param name="user">User user</param>
 /// <param name="group">string password</param>
 public void SetUserPassword(User user, string password)
 {
     try
     {
         if (
             database.Query("UPDATE Users SET Password = @0 WHERE Username = @1;", TShock.Utils.HashPassword(password),
                            user.Name) == 0)
             throw new UserNotExistException(user.Name);
     }
     catch (Exception ex)
     {
         throw new UserManagerException("SetUserPassword SQL returned an error", ex);
     }
 }
Beispiel #28
0
 public void UpdateLogin(User user)
 {
     try
     {
         if (database.Query("UPDATE Users SET LastAccessed = @0, KnownIps = @1 WHERE Username = @2;", DateTime.Now.ToString("G"), user.KnownIps, user.Name) == 0)
             throw new UserNotExistException(user.Name);
     }
     catch (Exception ex)
     {
         throw new UserManagerException("UpdateLogin SQL returned an error", ex);
     }
 }
Beispiel #29
0
 public TSServerPlayer()
     : base("Server")
 {
     Group = new SuperAdminGroup();
     User = new User{Name = AccountName};
 }
Beispiel #30
0
        private static void ManageUsers(CommandArgs args)
        {
            // This guy needs to be here so that people don't get exceptions when they type /user
            if (args.Parameters.Count < 1)
            {
                args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
                return;
            }

            string subcmd = args.Parameters[0];

            // Add requires a username, password, and a group specified.
            if (subcmd == "add"  && args.Parameters.Count == 4)
            {
                var user = new User();

                user.Name = args.Parameters[1];
                try
                {
                    user.CreateBCryptHash(args.Parameters[2]);
                }
                catch (ArgumentOutOfRangeException)
                {
                    args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
                    return;
                }
                user.Group = args.Parameters[3];

                try
                {
                    TShock.Users.AddUser(user);
                    args.Player.SendSuccessMessage("Account " + user.Name + " has been added to group " + user.Group + "!");
                    TShock.Log.ConsoleInfo(args.Player.Name + " added Account " + user.Name + " to group " + user.Group);
                }
                catch (GroupNotExistsException)
                {
                    args.Player.SendErrorMessage("Group " + user.Group + " does not exist!");
                }
                catch (UserExistsException)
                {
                    args.Player.SendErrorMessage("User " + user.Name + " already exists!");
                }
                catch (UserManagerException e)
                {
                    args.Player.SendErrorMessage("User " + user.Name + " could not be added, check console for details.");
                    TShock.Log.ConsoleError(e.ToString());
                }
            }
                // User deletion requires a username
            else if (subcmd == "del" && args.Parameters.Count == 2)
            {
                var user = new User();
                user.Name = args.Parameters[1];

                try
                {
                    TShock.Users.RemoveUser(user);
                    args.Player.SendSuccessMessage("Account removed successfully.");
                    TShock.Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + ".");
                }
                catch (UserNotExistException)
                {
                    args.Player.SendErrorMessage("The user " + user.Name + " does not exist! Deleted nobody!");
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendErrorMessage(ex.Message);
                    TShock.Log.ConsoleError(ex.ToString());
                }
            }

            // Password changing requires a username, and a new password to set
            else if (subcmd == "password" && args.Parameters.Count == 3)
            {
                var user = new User();
                user.Name = args.Parameters[1];

                try
                {
                    TShock.Users.SetUserPassword(user, args.Parameters[2]);
                    TShock.Log.ConsoleInfo(args.Player.Name + " changed the password of account " + user.Name);
                    args.Player.SendSuccessMessage("Password change succeeded for " + user.Name + ".");
                }
                catch (UserNotExistException)
                {
                    args.Player.SendErrorMessage("User " + user.Name + " does not exist!");
                }
                catch (UserManagerException e)
                {
                    args.Player.SendErrorMessage("Password change for " + user.Name + " failed! Check console!");
                    TShock.Log.ConsoleError(e.ToString());
                }
                catch (ArgumentOutOfRangeException)
                {
                    args.Player.SendErrorMessage("Password must be greater than or equal to " + TShock.Config.MinimumPasswordLength + " characters.");
                }
            }
            // Group changing requires a username or IP address, and a new group to set
            else if (subcmd == "group" && args.Parameters.Count == 3)
            {
                var user = new User();
                user.Name = args.Parameters[1];

                try
                {
                    TShock.Users.SetUserGroup(user, args.Parameters[2]);
                    TShock.Log.ConsoleInfo(args.Player.Name + " changed account " + user.Name + " to group " + args.Parameters[2] + ".");
                    args.Player.SendSuccessMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!");
                }
                catch (GroupNotExistsException)
                {
                    args.Player.SendErrorMessage("That group does not exist!");
                }
                catch (UserNotExistException)
                {
                    args.Player.SendErrorMessage("User " + user.Name + " does not exist!");
                }
                catch (UserManagerException e)
                {
                    args.Player.SendErrorMessage("User " + user.Name + " could not be added. Check console for details.");
                    TShock.Log.ConsoleError(e.ToString());
                }
            }
            else if (subcmd == "help")
            {
                args.Player.SendInfoMessage("Use command help:");
                args.Player.SendInfoMessage("{0}user add username password group   -- Adds a specified user", Specifier);
                args.Player.SendInfoMessage("{0}user del username                  -- Removes a specified user", Specifier);
                args.Player.SendInfoMessage("{0}user password username newpassword -- Changes a user's password", Specifier);
                args.Player.SendInfoMessage("{0}user group username newgroup       -- Changes a user's group", Specifier);
            }
            else
            {
                args.Player.SendErrorMessage("Invalid user syntax. Try {0}user help.", Specifier);
            }
        }
Beispiel #31
0
        private static void ManageUsers(CommandArgs args)
        {
            // This guy needs to be here so that people don't get exceptions when they type /user
            if (args.Parameters.Count < 1)
            {
                args.Player.SendErrorMessage("Invalid user syntax. Try /user help.");
                return;
            }

            string subcmd = args.Parameters[0];

            // Add requires a username:password pair/ip address and a group specified.
            if (subcmd == "add")
            {
                var namepass = args.Parameters[1].Split(':');
                var user = new User();

                try
                {
                    if (args.Parameters.Count > 2)
                    {
                        if (namepass.Length == 2)
                        {
                            user.Name = namepass[0];
                            user.Password = namepass[1];
                            user.Group = args.Parameters[2];
                        }
                        else if (namepass.Length == 1)
                        {
                            user.Address = namepass[0];
                            user.Group = args.Parameters[2];
                            user.Name = user.Address;
                        }
                        if (TShock.Users.GetUserByName(user.Name) == null)
                        {
                            if (!string.IsNullOrEmpty(user.Address))
                            {
                                args.Player.SendSuccessMessage("IP address admin added. If they're logged in, tell them to rejoin.");
                                args.Player.SendSuccessMessage("WARNING: This is insecure! It would be better to use a user account instead.");
                                TShock.Users.AddUser(user);
                                Log.ConsoleInfo(args.Player.Name + " added IP " + user.Address + " to group " + user.Group);
                            }
                            else
                            {
                                args.Player.SendSuccessMessage("Account " + user.Name + " has been added to group " + user.Group + "!");
                                TShock.Users.AddUser(user);
                                Log.ConsoleInfo(args.Player.Name + " added Account " + user.Name + " to group " + user.Group);
                            }
                        }
                        else
                        {
                            args.Player.SendErrorMessage("User already exists.");
                        }
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid syntax. Try /user help.");
                    }
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendErrorMessage(ex.Message);
                    Log.ConsoleError(ex.ToString());
                }
            }
                // User deletion requires a username
            else if (subcmd == "del" && args.Parameters.Count == 2)
            {
                var user = new User();
                if (args.Parameters[1].Split('.').Count() ==4)

                    //              changed to support dot character in usernames
                    //				if (args.Parameters[1].Contains("."))
                    user.Address = args.Parameters[1];
                else
                    user.Name = args.Parameters[1];

                try
                {
                    TShock.Users.RemoveUser(user);
                    args.Player.SendSuccessMessage("Account removed successfully.");
                    Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1] + ".");
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendMessage(ex.Message, Color.Red);
                    Log.ConsoleError(ex.ToString());
                }
            }
                // Password changing requires a username, and a new password to set
            else if (subcmd == "password")
            {
                var user = new User();
                user.Name = args.Parameters[1];

                try
                {
                    if (args.Parameters.Count == 3)
                    {
                        args.Player.SendSuccessMessage("Password change succeeded for " + user.Name + ".");
                        TShock.Users.SetUserPassword(user, args.Parameters[2]);
                        Log.ConsoleInfo(args.Player.Name + " changed the password of account " + user.Name);
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid user password syntax. Try /user help.");
                    }
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendErrorMessage(ex.Message);
                    Log.ConsoleError(ex.ToString());
                }
            }
                // Group changing requires a username or IP address, and a new group to set
            else if (subcmd == "group")
            {
                var user = new User();
                if (args.Parameters[1].Split('.').Count()==4)

                //changed to support dot character in usernames
                //if (args.Parameters[1].Contains("."))

                    user.Address = args.Parameters[1];
                else
                    user.Name = args.Parameters[1];

                try
                {
                    if (args.Parameters.Count == 3)
                    {
                        if (!string.IsNullOrEmpty(user.Address))
                        {
                            args.Player.SendSuccessMessage("IP address " + user.Address + " has been changed to group " + args.Parameters[2] + "!");
                            TShock.Users.SetUserGroup(user, args.Parameters[2]);
                            Log.ConsoleInfo(args.Player.Name + " changed IP address " + user.Address + " to group " + args.Parameters[2] + ".");
                        }
                        else
                        {
                            args.Player.SendSuccessMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!");
                            TShock.Users.SetUserGroup(user, args.Parameters[2]);
                            Log.ConsoleInfo(args.Player.Name + " changed account " + user.Name + " to group " + args.Parameters[2] + ".");
                        }
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Invalid user group syntax. Try /user help.");
                    }
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendMessage(ex.Message, Color.Green);
                    Log.ConsoleError(ex.ToString());
                }
            }
            else if (subcmd == "help")
            {
                args.Player.SendInfoMessage("Use command help:");
                args.Player.SendInfoMessage("/user add username:password group   -- Adds a specified user");
                args.Player.SendInfoMessage("/user del username                  -- Removes a specified user");
                args.Player.SendInfoMessage("/user password username newpassword -- Changes a user's password");
                args.Player.SendInfoMessage("/user group username newgroup       -- Changes a user's group");
            }
            else
            {
                args.Player.SendErrorMessage("Invalid user syntax. Try /user help.");
            }
        }
Beispiel #32
0
        //Todo: Add separate help text for '/user add' and '/user del'. Also add '/user addip' and '/user delip'
        private static void ManageUsers(CommandArgs args)
        {
            // This guy needs to go away for the help later on to take effect.

            //if (args.Parameters.Count < 2)
            //{
            //    args.Player.SendMessage("Syntax: /user <add/del> <ip/user:pass> [group]");
            //    args.Player.SendMessage("Note: Passwords are stored with SHA512 hashing. To reset a user's password, remove and re-add them.");
            //    return;
            //}

            // This guy needs to be here so that people don't get exceptions when they type /user
            if (args.Parameters.Count < 1)
            {
                args.Player.SendMessage("Invalid user syntax. Try /user help.", Color.Red);
                return;
            }

            string subcmd = args.Parameters[0];

            // Add requires a username:password pair/ip address and a group specified.
            if (subcmd == "add")
            {
                var namepass = args.Parameters[1].Split(':');
                var user = new User();

                try
                {
                    if (args.Parameters.Count > 2)
                    {
                        if (namepass.Length == 2)
                        {
                            user.Name = namepass[0];
                            user.Password = namepass[1];
                            user.Group = args.Parameters[2];
                        }
                        else if (namepass.Length == 1)
                        {
                            user.Address = namepass[0];
                            user.Group = args.Parameters[2];
                            user.Name = user.Address;
                        }
                        if (!string.IsNullOrEmpty(user.Address))
                        {
                            args.Player.SendMessage("IP address admin added. If they're logged in, tell them to rejoin.", Color.Green);
                            args.Player.SendMessage("WARNING: This is insecure! It would be better to use a user account instead.", Color.Red);
                            TShock.Users.AddUser(user);
                            Log.ConsoleInfo(args.Player.Name + " added IP " + user.Address + " to group " + user.Group);
                        }
                        else
                        {
                            args.Player.SendMessage("Account " + user.Name + " has been added to group " + user.Group + "!", Color.Green);
                            TShock.Users.AddUser(user);
                            Log.ConsoleInfo(args.Player.Name + " added Account " + user.Name + " to group " + user.Group);
                        }
                    }
                    else
                    {
                        args.Player.SendMessage("Invalid syntax. Try /user help.", Color.Red);
                    }
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendMessage(ex.Message, Color.Green);
                    Log.ConsoleError(ex.ToString());
                }
            }
            // User deletion requires a username
            else if (subcmd == "del" && args.Parameters.Count == 2)
            {
                var user = new User();
                if (args.Parameters[1].Contains("."))
                    user.Address = args.Parameters[1];
                else
                    user.Name = args.Parameters[1];

                try
                {
                    TShock.Users.RemoveUser(user);
                    args.Player.SendMessage("Account removed successfully.", Color.Green);
                    Log.ConsoleInfo(args.Player.Name + " successfully deleted account: " + args.Parameters[1]);
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendMessage(ex.Message, Color.Red);
                    Log.ConsoleError(ex.ToString());
                }
            }
            // Password changing requires a username, and a new password to set
            else if (subcmd == "password")
            {
                var user = new User();
                user.Name = args.Parameters[1];

                try
                {

                    if (args.Parameters.Count == 3)
                    {
                        args.Player.SendMessage("Changed the password of " + user.Name + "!", Color.Green);
                        TShock.Users.SetUserPassword(user, args.Parameters[2]);
                        Log.ConsoleInfo(args.Player.Name + " changed the password of Account " + user.Name);
                    }
                    else
                    {
                        args.Player.SendMessage("Invalid user password syntax. Try /user help.", Color.Red);
                    }
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendMessage(ex.Message, Color.Green);
                    Log.ConsoleError(ex.ToString());
                }
            }
            // Group changing requires a username or IP address, and a new group to set
            else if (subcmd == "group")
            {
                var user = new User();
                if (args.Parameters[1].Contains("."))
                    user.Address = args.Parameters[1];
                else
                    user.Name = args.Parameters[1];

                try
                {

                    if (args.Parameters.Count == 3)
                    {
                        if (!string.IsNullOrEmpty(user.Address))
                        {
                            args.Player.SendMessage("IP Address " + user.Address + " has been changed to group " + args.Parameters[2] + "!", Color.Green);
                            TShock.Users.SetUserGroup(user, args.Parameters[2]);
                            Log.ConsoleInfo(args.Player.Name + " changed IP Address " + user.Address + " to group " + args.Parameters[2]);
                        }
                        else
                        {
                            args.Player.SendMessage("Account " + user.Name + " has been changed to group " + args.Parameters[2] + "!", Color.Green);
                            TShock.Users.SetUserGroup(user, args.Parameters[2]);
                            Log.ConsoleInfo(args.Player.Name + " changed Account " + user.Name + " to group " + args.Parameters[2]);
                        }
                    }
                    else
                    {
                        args.Player.SendMessage("Invalid user group syntax. Try /user help.", Color.Red);
                    }
                }
                catch (UserManagerException ex)
                {
                    args.Player.SendMessage(ex.Message, Color.Green);
                    Log.ConsoleError(ex.ToString());
                }
            }
            else if (subcmd == "help")
            {
                args.Player.SendMessage("Help for user subcommands:");
                args.Player.SendMessage("/user add username:password group   -- Adds a specified user");
                args.Player.SendMessage("/user del username                  -- Removes a specified user");
                args.Player.SendMessage("/user password username newpassword -- Changes a user's password");
                args.Player.SendMessage("/user group username newgroup       -- Changes a user's group");
            }
            else
            {
                args.Player.SendMessage("Invalid user syntax. Try /user help.", Color.Red);
            }
        }
Beispiel #33
0
        public bool SeedInitialData(User user)
        {
            var inventory = new StringBuilder();

            var items = new List<NetItem>(TShock.ServerSideCharacterConfig.StartingInventory);
            if (items.Count < NetItem.MaxInventory)
                items.AddRange(new NetItem[NetItem.MaxInventory - items.Count]);

            string initialItems = String.Join("~", items.Take(NetItem.MaxInventory));
            try
            {
                database.Query("INSERT INTO tsCharacter (Account, Health, MaxHealth, Mana, MaxMana, Inventory, spawnX, spawnY, questsCompleted) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8);",
                               user.ID,
                               TShock.ServerSideCharacterConfig.StartingHealth,
                               TShock.ServerSideCharacterConfig.StartingHealth,
                               TShock.ServerSideCharacterConfig.StartingMana,
                               TShock.ServerSideCharacterConfig.StartingMana,
                               initialItems,
                               -1,
                               -1,
                               0);
                return true;
            }
            catch (Exception ex)
            {
                TShock.Log.Error(ex.ToString());
            }

            return false;
        }
Beispiel #34
0
        private void ER(CommandArgs args)
        {
            bool     addSubtract      = false;
            int      health           = 0;
            int      playerHealth     = 0;
            int      priorHealth      = 0;
            int      mana             = 0;
            int      playerMana       = 0;
            int      priorMana        = 0;
            string   playerName       = "";
            bool     noActionRequired = false;
            bool     playerActive     = false;
            TSPlayer player           = null;

            string arg;

            if (args.Parameters.Count == 0)
            {
                args.Player.SendMessage("Syntax: /EmergencyRoom <user> [flag] ", Color.Red);
                args.Player.SendMessage("Flags: ", Color.LightSalmon);
                args.Player.SendMessage("   -help             this information", Color.LightSalmon);
                args.Player.SendMessage("   -health/-h <+/-n> sets the MaxHealth of player to <n>", Color.LightSalmon);
                args.Player.SendMessage("   -mana/-m <+/-n>   sets the MaxMana of player to <n>", Color.LightSalmon);
                return;
            }

            arg = args.Parameters[0];
            {
                playerName = arg;
            }

            if (playerName.Length == 0)
            {
                args.Player.SendErrorMessage("No player name was given.");
                return;
            }

            if (playerName != args.Player.Name && !args.Player.Group.HasPermission("EmergencyRoom.allow.other"))
            {
                args.Player.SendErrorMessage("You do not have permissions to execute this command.");
                return;
            }

            TShockAPI.DB.User user = TShock.Users.GetUserByName(playerName);
            if (user == null)
            {
                args.Player.SendErrorMessage("Player " + playerName + " can't be found.");
                return;
            }

            playerActive = false;
            priorHealth  = 0;
            priorMana    = 0;
            var found = TShock.Utils.FindPlayer(playerName);

            if (found.Count == 1)
            {
                player       = (TSPlayer)found[0];
                playerActive = true;
            }
            else
            {
                playerActive = false;
            }

            try {
                using (var reader = TShock.DB.QueryReader("SELECT MaxHealth, MaxMana FROM tsCharacter where account =@0", user.ID)) {
                    if (reader.Read())
                    {
                        priorHealth = reader.Get <Int32>("MaxHealth");
                        priorMana   = reader.Get <Int32>("MaxMana");
                    }
                }
            }
            catch (Exception ex) {
                TShock.Log.Error(ex.ToString());
                Console.WriteLine(ex.StackTrace);
                return;
            }

            //            Console.WriteLine(user.Name + user.ID + " " + priorHealth + ":" + priorMana);
            playerHealth = priorHealth;
            playerMana   = priorMana;
            for (int i = 1; i < args.Parameters.Count; i++)
            {
                arg = args.Parameters[i];
                switch (arg)
                {
                case "-x":
                    if (!playerActive)
                    {
                        args.Player.SendErrorMessage("Player " + playerName + " can't be found.");
                        break;
                    }
                    break;

                case "-list":
                case "-l":
                    args.Player.SendInfoMessage("Player " + playerName + " MaxHealth currently at " + priorHealth + " and MaxMana currently at " + priorMana);
                    noActionRequired = true;
                    break;

                case "-h":
                    if (i + 1 >= args.Parameters.Count)
                    {
                        args.Player.SendErrorMessage("No value give for health");
                        noActionRequired = true;
                        break;
                    }
                    addSubtract = false;
                    if (args.Parameters[i + 1].StartsWith("+"))
                    {
                        addSubtract = true;
                    }
                    if (args.Parameters[i + 1].StartsWith("-"))
                    {
                        addSubtract = true;
                    }
                    if (Int32.TryParse(args.Parameters[i + 1], out health))
                    {
                        if (addSubtract)
                        {
                            if (playerHealth + health < 0)
                            {
                                args.Player.SendErrorMessage("Health value may not be negative");
                                noActionRequired = true;
                                i++;
                                break;
                            }
                            playerHealth = priorHealth + health;
                        }
                        else
                        {
                            playerHealth = health;
                        }
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Health value not an integer");
                        noActionRequired = true;
                        break;
                    }
                    i++;
                    break;

                case "-mana":
                case "-m":
                    if (i + 1 >= args.Parameters.Count)
                    {
                        args.Player.SendErrorMessage("No value give for mana");
                        noActionRequired = true;
                        break;
                    }
                    addSubtract = false;
                    if (args.Parameters[i + 1].StartsWith("+"))
                    {
                        addSubtract = true;
                    }
                    if (args.Parameters[i + 1].StartsWith("-"))
                    {
                        addSubtract = true;
                    }
                    if (Int32.TryParse(args.Parameters[i + 1], out mana))
                    {
                        if (addSubtract)
                        {
                            if (playerMana + mana < 0)
                            {
                                args.Player.SendErrorMessage("Mana value may not be negative");
                                noActionRequired = true;
                                i++;
                                break;
                            }
                            playerMana = priorMana + mana;
                        }
                        else
                        {
                            playerMana = mana;
                        }
                    }
                    else
                    {
                        args.Player.SendErrorMessage("Mana value not an integer");
                        noActionRequired = true;
                        i++;
                        break;
                    }
                    i++;
                    break;

                case "-help":
                    args.Player.SendMessage("Syntax: /EmergencyRoom <user> [-help] ", Color.Red);
                    args.Player.SendMessage("Flags: ", Color.LightSalmon);
                    args.Player.SendMessage("   -help             this information", Color.LightSalmon);
                    args.Player.SendMessage("   -health/-h <+/-n> sets the MaxHealth of player to <n>", Color.LightSalmon);
                    args.Player.SendMessage("   -mana/-m <+/-n>   sets the MaxMana of player to <n>", Color.LightSalmon);
                    return;

                default:
                    args.Player.SendErrorMessage("Unkonown command argument:" + arg);
                    noActionRequired = true;
                    return;
                }
            }
            if (noActionRequired)
            {
                return;
            }

            if (playerActive)
            {
                player.TPlayer.statManaMax = playerMana;
                player.TPlayer.statLifeMax = playerHealth;
                player.SendData(PacketTypes.PlayerHp, player.Name, player.Index);
                //                player.SendData(PacketTypes.EffectMana, player.Name, player.Index);
                player.SendData(PacketTypes.PlayerMana, player.Name, player.Index);
                player.SendData(PacketTypes.PlayerUpdate, player.Name, player.Index);
            }

            try {
                using (var reader = TShock.DB.QueryReader("UPDATE tsCharacter SET  MaxHealth = @0, MaxMana = @1 WHERE Account = @2;", playerHealth, playerMana, user.ID)) {
                }
            }
            catch (Exception ex) {
                args.Player.SendInfoMessage("Player " + playerName + " no database change.");
                TShock.Log.Error(ex.ToString());
                Console.WriteLine(ex.StackTrace);
                return;
            }
            string message = "";

            if (priorHealth != playerHealth)
            {
                message = " MaxHealth changed from " + priorHealth + " to " + playerHealth;
            }
            if (priorMana != playerMana)
            {
                message += " MaxMana changed from " + priorMana + " to " + playerMana;
            }
            args.Player.SendInfoMessage("Player " + playerName + message);
        }
Beispiel #35
0
		/// <summary>
		/// Initializes a new instance of the <see cref="Contributor"/> class from the given
		/// <paramref name="user"/> account.
		/// </summary>
		/// <param name="user">The user account to be registered to this contributor.</param>
		public Contributor(User user) : this(0)
		{
			Accounts.Add(user.ID);
		}
Beispiel #36
0
 public AccountDeleteEventArgs(User user)
 {
     this.User = user;
 }
Beispiel #37
0
 /// <summary>
 /// Sets the UUID for a given username
 /// </summary>
 /// <param name="user">User user</param>
 /// <param name="group">string uuid</param>
 public void SetUserUUID(User user, string uuid)
 {
     try
     {
         if (
             database.Query("UPDATE Users SET UUID = @0 WHERE Username = @1;", uuid,
                            user.Name) == 0)
             throw new UserNotExistException(user.Name);
     }
     catch (Exception ex)
     {
         throw new UserManagerException("SetUserUUID SQL returned an error", ex);
     }
 }