Ejemplo n.º 1
0
 public static void DisplaySearchResults(TSPlayer Player, List<object> Results, int Page)
 {
     if (Results[0] is Item)
         Player.SendInfoMessage("Item Search:");
     else if (Results[0] is NPC)
         Player.SendInfoMessage("NPC Search:");
     var sb = new StringBuilder();
     if (Results.Count > (8 * (Page - 1)))
     {
         for (int j = (8 * (Page - 1)); j < (8 * Page); j++)
         {
             if (sb.Length != 0)
                 sb.Append(" | ");
             if (Results[j] is Item)
                 sb.Append(((Item)Results[j]).netID).Append(": ").Append(((Item)Results[j]).name);
             else if (Results[j] is NPC)
                 sb.Append(((NPC)Results[j]).netID).Append(": ").Append(((NPC)Results[j]).name);
             if (j == Results.Count - 1)
             {
                 Player.SendSuccessMessage(sb.ToString());
                 break;
             }
             if ((j + 1) % 2 == 0)
             {
                 Player.SendSuccessMessage(sb.ToString());
                 sb.Clear();
             }
         }
     }
     if (Results.Count > (8 * Page))
     {
         Player.SendInfoMessage("Type /spage {0} for more Results.", Page + 1);
     }
 }
Ejemplo n.º 2
0
        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);
        }
Ejemplo n.º 3
0
 public static void Success(TSPlayer to, string message)
 {
     if (to is TSServerPlayer)
     {
         to.SendSuccessMessage(message);
         return;
     }
     to.SendMessage(message, Color.MediumSeaGreen);
 }
Ejemplo n.º 4
0
 public static void DisplaySearchResults(TSPlayer Player, string type, Dictionary<string, int> Results, int Page)
 {
     Player.SendInfoMessage(type + " Search:");
       var sb = new StringBuilder();
       if (Results.Count > (8 * (Page - 1))) {
     for (int j = (8 * (Page - 1)); j < (8 * Page); j++) {
       if (sb.Length != 0)
     sb.Append(" | ");
       sb.Append(Results.ElementAt(j).Key).Append(": ").Append(Results.ElementAt(j).Value);
       if (j == Results.Count - 1) {
     Player.SendSuccessMessage(sb.ToString());
     break;
       }
       if ((j + 1) % 2 == 0) {
     Player.SendSuccessMessage(sb.ToString());
     sb.Clear();
       }
     }
       }
       if (Results.Count > (8 * Page)) {
     Player.SendInfoMessage("Type /spage {0} for more Results.", Page + 1);
       }
 }
        private bool TryCreateAutoProtection(TSPlayer forPlayer, DPoint location)
        {
            try {
            this.ProtectionManager.CreateProtection(forPlayer, location, false);

            if (this.Config.NotifyAutoProtections)
              forPlayer.SendSuccessMessage(string.Format("This {0} has been protected.", TerrariaUtils.Tiles.GetBlockTypeName((BlockType)TerrariaUtils.Tiles[location].type)));

            return true;
              } catch (PlayerNotLoggedInException) {
            forPlayer.SendWarningMessage(string.Format(
              "This {0} will not be protected because you're not logged in.", TerrariaUtils.Tiles.GetBlockTypeName((BlockType)TerrariaUtils.Tiles[location].type)
            ));
              } catch (LimitEnforcementException) {
            forPlayer.SendWarningMessage(string.Format(
              "This {0} will not be protected because you've reached the protection limit.", TerrariaUtils.Tiles.GetBlockTypeName((BlockType)TerrariaUtils.Tiles[location].type)
            ));
              } catch (TileProtectedException) {
            this.PluginTrace.WriteLineError("Error: A block was tried to be auto protected where tile placement should not be possible.");
              } catch (AlreadyProtectedException) {
            this.PluginTrace.WriteLineError("Error: A block was tried to be auto protected on the same position of an existing protection.");
              } catch (Exception ex) {
            this.PluginTrace.WriteLineError("Unexpected exception was thrown during auto protection: \n" + ex);
              }

              return false;
        }
        private bool TryAlterProtectionShare(
            TSPlayer player, DPoint tileLocation, bool isShareOrUnshare, bool isGroup, bool isShareAll,
            object shareTarget, string shareTargetName, bool sendFailureMessages = true
            )
        {
            if (!player.IsLoggedIn) {
            if (sendFailureMessages)
              player.SendErrorMessage("You have to be logged in to alter protections.");

            return false;
              }

              try {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            if (isShareAll) {
              this.ProtectionManager.ProtectionShareAll(player, tileLocation, isShareOrUnshare, true);

              if (isShareOrUnshare) {
            player.SendSuccessMessage(string.Format(
              "This {0} is now shared with everyone.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
            ));
              } else {
            player.SendSuccessMessage(string.Format(
              "This {0} is not shared with everyone anymore.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
            ));
              }
            } else if (!isGroup) {
              this.ProtectionManager.ProtectionShareUser(player, tileLocation, (int)shareTarget, isShareOrUnshare, true);

              if (isShareOrUnshare) {
            player.SendSuccessMessage(string.Format(
              "This {0} is now shared with player \"{1}\".",
              TerrariaUtils.Tiles.GetBlockTypeName(blockType), shareTargetName
            ));
              } else {
            player.SendSuccessMessage(string.Format(
              "This {0} is not shared with player \"{1}\" anymore.",
              TerrariaUtils.Tiles.GetBlockTypeName(blockType), shareTargetName
            ));
              }
            } else {
              this.ProtectionManager.ProtectionShareGroup(player, tileLocation, (string)shareTarget, isShareOrUnshare, true);

              if (isShareOrUnshare) {
            player.SendSuccessMessage(string.Format(
              "This {0} is now shared with group \"{1}\".",
              TerrariaUtils.Tiles.GetBlockTypeName(blockType), shareTargetName
            ));
              } else {
            player.SendSuccessMessage(string.Format(
              "This {0} is not shared with group \"{1}\" anymore.",
              TerrariaUtils.Tiles.GetBlockTypeName(blockType), shareTargetName
            ));
              }
            }

            return true;
              } catch (ProtectionAlreadySharedException) {
            string blockName = TerrariaUtils.Tiles.GetBlockTypeName((BlockType)TerrariaUtils.Tiles[tileLocation].type);

            if (isShareAll) {
              player.SendErrorMessage(string.Format("This {0} is already shared with everyone.", blockName));
            } else if (!isGroup) {
              player.SendErrorMessage(string.Format("This {0} is already shared with {1}.", blockName, shareTargetName));
            } else {
              player.SendErrorMessage(string.Format(
            "This {0} is already shared with group {1}.", blockName, shareTargetName
              ));
            }

            return false;
              } catch (ProtectionNotSharedException) {
            string blockName = TerrariaUtils.Tiles.GetBlockTypeName((BlockType)TerrariaUtils.Tiles[tileLocation].type);

            if (isShareAll) {
              player.SendErrorMessage(string.Format("This {0} isn't shared with everyone.", blockName));
            } else if (!isGroup) {
              player.SendErrorMessage(string.Format("This {0} isn't shared with {1}.", blockName, shareTargetName));
            } else {
              player.SendErrorMessage(string.Format(
            "This {0} isn't shared with group {1}.", blockName, shareTargetName
              ));
            }

            return false;
              } catch (InvalidBlockTypeException ex) {
            if (sendFailureMessages) {
              string messageFormat;
              if (TerrariaUtils.Tiles.IsSolidBlockType(ex.BlockType, true))
            messageFormat = "Protections of {0} blocks are not shareable.";
              else
            messageFormat = "Protections of {0} objects are not shareable.";

              player.SendErrorMessage(string.Format(messageFormat, TerrariaUtils.Tiles.GetBlockTypeName(ex.BlockType)));
            }

            return false;
              } catch (MissingPermissionException ex) {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            if (sendFailureMessages) {
              if (ex.Permission == ProtectorPlugin.BankChestShare_Permission) {
            player.SendErrorMessage("You're not allowed to share bank chests.");
              } else {
            player.SendErrorMessage(string.Format(
              "You're not allowed to share {0} objects.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
            ));
              }
            }

            return false;
              } catch (NoProtectionException) {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            if (sendFailureMessages) {
              player.SendErrorMessage(string.Format(
            "This {0} is not protected by Protector at all.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
              ));
            }

            return false;
              } catch (TileProtectedException) {
            if (sendFailureMessages)
              player.SendErrorMessage("You have to be the owner in order to alter shares of the protection.");

            return false;
              }
        }
        private void PerformTrade(TSPlayer player, ProtectionEntry protection, Inventory chestInventory, Item sellItem, Item payItem)
        {
            Inventory playerInventory = new Inventory(new PlayerItemsAdapter(player.Index, player.TPlayer.inventory, 0, 53), specificPrefixes: false);

              ItemData sellItemData = ItemData.FromItem(sellItem);
              ItemData payItemData = ItemData.FromItem(payItem);
              ItemData?[] playerInvUpdates;
              try {
            playerInvUpdates = playerInventory.Remove(payItemData);
            playerInventory.Add(playerInvUpdates, sellItemData);
              } catch (InvalidOperationException) {
            player.SendErrorMessage($"You either don't have the needed {TShock.Utils.ItemTag(payItem)} to purchase {TShock.Utils.ItemTag(sellItem)} or your inventory is full.");
            return;
              }

              bool isRefillChest = (protection.RefillChestData != null);
              ItemData?[] chestInvUpdates;
              try {
            if (isRefillChest) {
              chestInvUpdates = chestInventory.Add(payItemData);
            } else {
              chestInvUpdates = chestInventory.Remove(sellItemData);
              chestInventory.Add(chestInvUpdates, payItemData);
            }
              } catch (InvalidOperationException) {
            player.SendErrorMessage("The items in the trade chest are either sold out or there's no space in it to add your payment.");
            return;
              }

              try {
            protection.TradeChestData.AddOrUpdateLooter(player.User.ID);
              } catch (InvalidOperationException) {
            player.SendErrorMessage($"The vendor doesn't allow more than {protection.TradeChestData.LootLimitPerPlayer} purchases per player.");
            return;
              }

              playerInventory.ApplyUpdates(playerInvUpdates);
              chestInventory.ApplyUpdates(chestInvUpdates);

              protection.TradeChestData.AddJournalEntry(player.Name, sellItem, payItem);
              player.SendSuccessMessage($"You've just purchased {TShock.Utils.ItemTag(sellItem)} for {TShock.Utils.ItemTag(payItem)} from {TShock.Utils.ColorTag(GetUserName(protection.Owner), Color.Red)}.");
        }
        public bool TrySetUpTradeChest(TSPlayer player, DPoint tileLocation, int sellAmount, int sellItemId, int payAmount, int payItemId, int lootLimit = 0, bool sendMessages = true)
        {
            if (!player.IsLoggedIn) {
            if (sendMessages)
              player.SendErrorMessage("You have to be logged in in order to set up trade chests.");

            return false;
              }

              if (!this.ProtectionManager.CheckBlockAccess(player, tileLocation, true) && !player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission)) {
            player.SendErrorMessage("You don't own the protection of this chest.");
            return false;
              }

              try {
            this.ChestManager.SetUpTradeChest(player, tileLocation, sellAmount, sellItemId, payAmount, payItemId, lootLimit, true);

            player.SendSuccessMessage("Trade chest was successfully created / updated.");
            return true;
              } catch (ArgumentOutOfRangeException ex) {
            if (sendMessages)
              player.SendErrorMessage("Invalid item amount given.");

            return false;
              } catch (ArgumentException ex) {
            if (ex.ParamName == "tileLocation") {
              if (sendMessages)
            player.SendErrorMessage("There is no chest here.");

              return false;
            }

            throw;
              } catch (MissingPermissionException) {
            if (sendMessages)
              player.SendErrorMessage("You are not allowed to define trade chests.");
              } catch (PaymentException ex) {
            if (sendMessages)
              player.SendErrorMessage("You don't have the necessary amount of {0} {1} to set up a trade chest!", ex.PaymentAmount, this.PluginCooperationHandler.Seconomy_MoneyName());
              } catch (InvalidBlockTypeException) {
            if (sendMessages)
              player.SendErrorMessage("Only chests can be converted to trade chests.");
              } catch (NoProtectionException) {
            if (sendMessages)
              player.SendErrorMessage("The chest needs to be protected to be converted to a trade chest.");
              } catch (ChestTypeAlreadyDefinedException) {
            if (sendMessages)
              player.SendErrorMessage("The chest is already a trade chest.");
              } catch (ChestIncompatibilityException) {
            if (sendMessages)
              player.SendErrorMessage("A trade chest can not be a bank chest at the same time.");
              } catch (NoChestDataException) {
            if (sendMessages)
              player.SendErrorMessage("Error: There are no chest data for this chest available. This world's data might be corrupted.");
              }

              return false;
        }
Ejemplo n.º 9
0
        public static void SendPage(
			TSPlayer player, int pageNumber, Dictionary<string, int> dictionary, int dataToPaginateCount,
			FormatSettings settings = null)
        {
            if (settings == null)
                settings = new FormatSettings();

            if (dataToPaginateCount == 0)
            {
                if (settings.NothingToDisplayString != null)
                {
                    if (!player.RealPlayer)
                        player.SendSuccessMessage(settings.NothingToDisplayString);
                    else
                        player.SendMessage(settings.NothingToDisplayString, settings.HeaderTextColor);
                }
                return;
            }

            var pageCount = ((dataToPaginateCount - 1)/settings.MaxLinesPerPage) + 1;
            if (settings.PageLimit > 0 && pageCount > settings.PageLimit)
                pageCount = settings.PageLimit;
            if (pageNumber > pageCount)
                pageNumber = pageCount;

            if (settings.IncludeHeader)
            {
                if (!player.RealPlayer)
                    player.SendSuccessMessage(string.Format(settings.HeaderFormat, pageNumber, pageCount));
                else
                    player.SendMessage(string.Format(settings.HeaderFormat, pageNumber, pageCount),
                        settings.HeaderTextColor);
            }

            var listOffset = (pageNumber - 1)*settings.MaxLinesPerPage;
            var offsetCounter = 0;
            var lineCounter = 0;

            foreach (var lineData in dictionary)
            {
                if (offsetCounter++ < listOffset)
                    continue;
                if (lineCounter++ == settings.MaxLinesPerPage)
                    break;

                var lineColor = Color.Yellow;
                var hsName = lineData.Key;
                var hsScore = lineData.Value;
                var index = dictionary.Keys.ToList().IndexOf(hsName) + 1;

                if (index == 1)
                    lineColor = Color.Cyan;
                if (index == 2)
                    lineColor = Color.ForestGreen;
                if (index == 3)
                    lineColor = Color.OrangeRed;

                if (string.Equals(hsName, player.UserAccountName, StringComparison.CurrentCultureIgnoreCase))
                    lineColor = Color.White;

                if (!string.IsNullOrEmpty(hsName))
                {
                    if (!player.RealPlayer)
                        player.SendInfoMessage("{0}. {1} with {2} point{3}",
                            index, hsName, hsScore, hsScore.Suffix());
                    else
                        player.SendMessage(string.Format("{0}. {1} with {2} point{3}",
                            index, hsName, hsScore, hsScore.Suffix()), lineColor);
                }
            }

            if (lineCounter == 0)
            {
                if (settings.NothingToDisplayString != null)
                {
                    if (!player.RealPlayer)
                        player.SendSuccessMessage(settings.NothingToDisplayString);
                    else
                        player.SendMessage(settings.NothingToDisplayString, settings.HeaderTextColor);
                }
            }
            else if (settings.IncludeFooter && pageNumber + 1 <= pageCount)
            {
                if (!player.RealPlayer)
                    player.SendInfoMessage(string.Format(settings.FooterFormat, pageNumber + 1, pageNumber, pageCount));
                else
                    player.SendMessage(string.Format(settings.FooterFormat, pageNumber + 1, pageNumber, pageCount),
                        settings.FooterTextColor);
            }
        }
Ejemplo n.º 10
0
        public static void SendPage(
            TSPlayer player, int pageNumber, IEnumerable dataToPaginate, int dataToPaginateCount, Settings settings = null)
        {
            if (settings == null)
                settings = new Settings();

            if (dataToPaginateCount == 0)
            {
                if (settings.NothingToDisplayString != null)
                {
                    if (!player.RealPlayer)
                        player.SendSuccessMessage(settings.NothingToDisplayString);
                    else
                        player.SendMessage(settings.NothingToDisplayString, settings.HeaderTextColor);
                }
                return;
            }

            int pageCount = ((dataToPaginateCount - 1) / settings.MaxLinesPerPage) + 1;
            if (settings.PageLimit > 0 && pageCount > settings.PageLimit)
                pageCount = settings.PageLimit;
            if (pageNumber > pageCount)
                pageNumber = pageCount;

            if (settings.IncludeHeader)
            {
                if (!player.RealPlayer)
                    player.SendSuccessMessage(string.Format(settings.HeaderFormat, pageNumber, pageCount));
                else
                    player.SendMessage(string.Format(settings.HeaderFormat, pageNumber, pageCount), settings.HeaderTextColor);
            }

            int listOffset = (pageNumber - 1) * settings.MaxLinesPerPage;
            int offsetCounter = 0;
            int lineCounter = 0;
            foreach (object lineData in dataToPaginate)
            {
                if (lineData == null)
                    continue;
                if (offsetCounter++ < listOffset)
                    continue;
                if (lineCounter++ == settings.MaxLinesPerPage)
                    break;

                string lineMessage;
                Color lineColor = settings.LineTextColor;
                if (lineData is Tuple<string, Color>)
                {
                    var lineFormat = (Tuple<string, Color>)lineData;
                    lineMessage = lineFormat.Item1;
                    lineColor = lineFormat.Item2;
                }
                else if (settings.LineFormatter != null)
                {
                    try
                    {
                        Tuple<string, Color> lineFormat = settings.LineFormatter(lineData, offsetCounter, pageNumber);
                        if (lineFormat == null)
                            continue;

                        lineMessage = lineFormat.Item1;
                        lineColor = lineFormat.Item2;
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException(
                          "The method referenced by LineFormatter has thrown an exception. See inner exception for details.", ex);
                    }
                }
                else
                {
                    lineMessage = lineData.ToString();
                }

                if (lineMessage != null)
                {
                    if (!player.RealPlayer)
                        player.SendInfoMessage(lineMessage);
                    else
                        player.SendMessage(lineMessage, lineColor);
                }
            }

            if (lineCounter == 0)
            {
                if (settings.NothingToDisplayString != null)
                {
                    if (!player.RealPlayer)
                        player.SendSuccessMessage(settings.NothingToDisplayString);
                    else
                        player.SendMessage(settings.NothingToDisplayString, settings.HeaderTextColor);
                }
            }
            else if (settings.IncludeFooter && pageNumber + 1 <= pageCount)
            {
                if (!player.RealPlayer)
                    player.SendInfoMessage(string.Format(settings.FooterFormat, pageNumber + 1, pageNumber, pageCount));
                else
                    player.SendMessage(string.Format(settings.FooterFormat, pageNumber + 1, pageNumber, pageCount), settings.FooterTextColor);
            }
        }
        public virtual bool HandleChestModifySlot(TSPlayer player, int chestIndex, int slotIndex, ItemData newItem)
        {
            if (this.IsDisposed)
            return false;

              // Get the chest location of the chest the player has last opened.
              IChest chest = this.LastOpenedChest(player);
              if (chest == null)
            return true;

              ProtectionEntry protection = null;
              // Only need the first enumerated entry as we don't need the protections of adjacent blocks.
              foreach (ProtectionEntry enumProtection in this.ProtectionManager.EnumerateProtectionEntries(chest.Location)) {
            protection = enumProtection;
            break;
              }

              bool playerHasAccess = true;
              if (protection != null)
            playerHasAccess = this.ProtectionManager.CheckProtectionAccess(protection, player, false);

              if (!playerHasAccess)
            return true;

              if (protection != null && protection.RefillChestData != null) {
            RefillChestMetadata refillChest = protection.RefillChestData;
            // The player who set up the refill chest or masters shall modify its contents.
            if (
              this.Config.AllowRefillChestContentChanges &&
              (refillChest.Owner == player.User.ID || player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission))
            ) {
              refillChest.RefillItems[slotIndex] = newItem;

              this.ChestManager.TryRefillChest(chest, refillChest);

              if (refillChest.RefillTime == TimeSpan.Zero) {
            player.SendSuccessMessage("The content of this refill chest was updated.");
              } else {
            lock (this.ChestManager.RefillTimers) {
              if (this.ChestManager.RefillTimers.IsTimerRunning(refillChest.RefillTimer))
                this.ChestManager.RefillTimers.RemoveTimer(refillChest.RefillTimer);
            }

            player.SendSuccessMessage("The content of this refill chest was updated and the timer was reset.");
              }

              return false;
            }

            if (refillChest.OneLootPerPlayer || refillChest.RemainingLoots > 0) {
              Contract.Assert(refillChest.Looters != null);
              if (!refillChest.Looters.Contains(player.User.ID)) {
            refillChest.Looters.Add(player.User.ID);

            if (refillChest.RemainingLoots > 0)
              refillChest.RemainingLoots--;
              }
            }

            // As the first item is taken out, we start the refill timer.
            ItemData oldItem = chest.Items[slotIndex];
            if (newItem.Type == ItemType.None || (newItem.Type == oldItem.Type && newItem.StackSize <= oldItem.StackSize)) {
              // TODO: Bad code, refill timers shouldn't be public at all.
              lock (this.ChestManager.RefillTimers)
            this.ChestManager.RefillTimers.StartTimer(refillChest.RefillTimer);
            } else {
              player.SendErrorMessage("You can not put items into this chest.");
              return true;
            }
              } else if (protection != null && protection.BankChestKey != BankChestDataKey.Invalid) {
            BankChestDataKey bankChestKey = protection.BankChestKey;
            this.ServerMetadataHandler.EnqueueUpdateBankChestItem(bankChestKey, slotIndex, newItem);
              }

              chest.Items[slotIndex] = newItem;
              return true;
        }
Ejemplo n.º 12
0
        public void Update(TSPlayer player)
        {
            if ((DateTime.Now - lastDisabled).TotalSeconds > 10)
            {
                disabled = false;
                lastDisabled = DateTime.Now;
            }

            bool bypassFlag = BypassFlag(player);

            bool warning = ((DateTime.Now - lastWarned).TotalSeconds > 1);
            if (regionStorage.flags.Contains("HEAL"))
            {
                if (regionStorage.healinterval < 0 || regionStorage.healamount < 0)
                    return;
                if ((DateTime.Now - lastHealUpdate).TotalSeconds >= regionStorage.healinterval)
                {
                    lastHealUpdate = DateTime.Now;
                    player.Heal(regionStorage.healamount);
                }
            }
            if (regionStorage.flags.Contains("MANA"))
            {
                if (regionStorage.manainterval < 0 || regionStorage.healamount < 0)
                    return;
                if ((DateTime.Now - lastManaUpdate).TotalSeconds >= regionStorage.manainterval)
                {
                    lastManaUpdate = DateTime.Now;
                    var matches = TShock.Utils.GetItemByIdOrName("184");
                    Item star = matches[0];
                    player.GiveItem(star.netID, star.name, star.width, star.height, regionStorage.healamount);
                }
            }
            if (regionStorage.flags.Contains("PRIVATE") && !bypassFlag)
            {
                if (!gotWarnMessage)
                {
                    player.Teleport(lastPos.X, lastPos.Y, 1);
                    player.SendErrorMessage("No permission to enter private region!");
                    gotWarnMessage = true;
                }
            }
            if (regionStorage.flags.Contains("PVP") && !bypassFlag)
            {
                if (!player.TPlayer.hostile)
                {
                    player.SendSuccessMessage("PVP arena entered, pvp enabled.");
                    player.TPlayer.hostile = true;
                    NetMessage.SendData((int)PacketTypes.TogglePvp, -1, -1, "", player.Index);
                }
            }
            if (regionStorage.flags.Contains("NOPVP") && !bypassFlag)
            {
                if (player.TPlayer.hostile)
                {
                    player.SendSuccessMessage("PVP arena entered, pvp disabled.");
                    player.TPlayer.hostile = false;
                    NetMessage.SendData((int)PacketTypes.TogglePvp, -1, -1, "", player.Index);
                }
            }
            if (regionStorage.flags.Contains("TEMPGROUP") && !bypassFlag)
            {
                if (!groupset)
                {
                    player.tempGroup = regionStorage.tempgroup;
                    player.SendSuccessMessage("Your group has been temporarily set to \"{0}\"!", regionStorage.tempgroup.Name);
                    groupset = true;
                }
            }
            if (regionStorage.flags.Contains("DEATH") && !bypassFlag)
            {
                if (!killed)
                {
                    player.DamagePlayer(1200);
                    player.SendErrorMessage("You entered a death zone! RIP");
                    killed = true;
                }
            }
            if (regionStorage.flags.Contains("HURT") && !bypassFlag)
            {
                if (regionStorage.damageinterval < 0 || regionStorage.damageamount< 0)
                    return;
                if ((DateTime.Now - lastDamageUpdate).TotalSeconds >= regionStorage.damageinterval)
                {
                    lastDamageUpdate = DateTime.Now;
                    player.DamagePlayer(regionStorage.damageamount);
                }
            }
            if (regionStorage.flags.Contains("COMMAND") && !bypassFlag)
            {
                if (!executedcommand)
                {
                    if (regionStorage.command != null && regionStorage.command != "")
                    {
                        Commands.HandleCommand(TSPlayer.Server, "/" + regionStorage.command);
                        executedcommand = true;
                    }
                }
            }
            if (regionStorage.flags.Contains("PROMOTE") && !bypassFlag)
            {
                if (!promoted)
                {
                    if (player.Group == TShock.Groups.GetGroupByName(regionStorage.fromgroup) || regionStorage.fromgroup == "*")
                    {
                        player.Group = TShock.Groups.GetGroupByName(regionStorage.togroup);
                        player.SendInfoMessage("You have been promoted to group \"{0}\"", regionStorage.togroup);
                        promoted = true;
                    }
                }
            }
            if (regionStorage.flags.Contains("GROUPONLY"))
            {
                if (!gotWarnMessage && !regionStorage.groupOnly.Contains(player.Group.Name) && !bypassFlag)
                {
                    player.Teleport(lastPos.X, lastPos.Y, 1);
                    player.SendErrorMessage("No permission to enter private region!");
                    gotWarnMessage = true;
                }
            }
            if (regionStorage.flags.Contains("MESSAGE"))
            {
                if (!gotmessage)
                {
                    if (regionStorage.message != null && regionStorage.message != "")
                    {
                        player.SendInfoMessage(regionStorage.message);
                        gotmessage = true;
                    }
                }
            }
        }
Ejemplo n.º 13
0
        public static bool ReadConfig(string fname, TSPlayer plr, bool statistics)
        {
            string filepath = Path.Combine(TShock.SavePath, "Classes", fname);

            try
            {
                if (File.Exists(filepath))
                {
                    using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (var sr = new StreamReader(stream))
                        {
                            var configString = sr.ReadToEnd();
                            if (statistics)
                                stats = JsonConvert.DeserializeObject<Stats>(configString);
                            else
                            {
                                contents = JsonConvert.DeserializeObject<Contents>(configString);
                                contents.playerClasses.RemoveRange(0, 3);//Delete default classes
                            }
                        }
                        stream.Close();
                    }
                    return true;
                }
                else
                {
                    CreateConfig(fname, statistics);
                    Log.ConsoleInfo(String.Format("Created {0}", fname));
                    plr.SendSuccessMessage(String.Format("Created {0}", fname));
                    return true;
                }
            }
            catch (Exception e)
            {
                Log.ConsoleError(e.Message);
            }
            return false;
        }
Ejemplo n.º 14
0
        public static void getSpawnGroup(string nGroup, TSPlayer player)
        {
            bool flag = false;
            for (int i = 0; i < MAC.config.SpawnGroupNPCs.Count; i++)
            {
                for (int j = 0; j < MAC.config.SpawnGroupNPCs[i].NPCList.Count; j++)
                {
                    var checkGroup = MAC.config.SpawnGroupNPCs[i].NPCList[j];

                    if (checkGroup.groupname == nGroup)
                    {
                        foreach (KeyValuePair<string, int> pair in checkGroup.npcDetails)
                        {
                            var mobs = TShock.Utils.GetNPCByName(pair.Key);

                            TSPlayer.Server.SpawnNPC(mobs[0].type, mobs[0].name, pair.Value,
                                (int)player.X, (int)player.Y, 30, 30);
                        }
                        player.SendSuccessMessage("Spawned mobs from group " + nGroup);
                    }
                }
            }
        }
Ejemplo n.º 15
0
        private void setUpConfig(TSPlayer player = null)
        {
            try
            {
                if (File.Exists(configPath))
                    config = eConfig.Read(configPath);

                else
                    config.Write(configPath);

                if (player != null)
                    player.SendSuccessMessage("Reloaded event stopper plugin's configuration");
            }
            catch (Exception x)
            {
                Log.ConsoleError("Error occured on reloading event stopper plugin's configuration");
                Log.ConsoleError(x.ToString());
                player.SendErrorMessage("Error occured on reloading event stopper plugin's configuration");
                player.SendErrorMessage(x.Message);
            }
        }
        private bool TryCreateProtection(TSPlayer player, DPoint tileLocation, bool sendFailureMessages = true)
        {
            if (!player.IsLoggedIn) {
            if (sendFailureMessages)
              player.SendErrorMessage("You have to be logged in in order protect blocks or objects.");

            return false;
              }

              try {
            this.ProtectionManager.CreateProtection(player, tileLocation);

            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            player.SendSuccessMessage(string.Format("This {0} is now protected.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)));

            return true;
              } catch (ArgumentException ex) {
            if (ex.ParamName == "tileLocation" && sendFailureMessages)
              player.SendErrorMessage("Nothing to protect here.");

            throw;
              } catch (InvalidBlockTypeException ex) {
            if (sendFailureMessages) {
              string messageFormat;
              if (TerrariaUtils.Tiles.IsSolidBlockType(ex.BlockType, true))
            messageFormat = "Blocks of type {0} can not be protected.";
              else
            messageFormat = "Objects of type {0} can not be protected.";

              player.SendErrorMessage(string.Format(messageFormat, TerrariaUtils.Tiles.GetBlockTypeName(ex.BlockType)));
            }
              } catch (LimitEnforcementException) {
            if (sendFailureMessages) {
              player.SendErrorMessage(
            string.Format("You can't create new protections because you've reached the maximum number of protections: {0}.",
            this.Config.MaxProtectionsPerPlayerPerWorld)
              );
            }
              } catch (AlreadyProtectedException) {
            if (sendFailureMessages) {
              BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
              player.SendErrorMessage(string.Format("This {0} is already protected.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)));
            }
              } catch (TileProtectedException) {
            if (sendFailureMessages) {
              BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
              player.SendErrorMessage(string.Format("This {0} is protected by someone else or is inside of a protected region.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)));
            }
              } catch (Exception ex) {
            player.SendErrorMessage("An unexpected internal error occured.");
            this.PluginTrace.WriteLineError("Error on creating protection: ", ex.ToString());

              }

              return false;
        }
        private bool TryRemoveProtection(TSPlayer player, DPoint tileLocation, bool sendFailureMessages = true)
        {
            if (!player.IsLoggedIn) {
            if (sendFailureMessages)
              player.SendErrorMessage("You have to be logged in to alter protections.");

            return false;
              }

              try {
            this.ProtectionManager.RemoveProtection(player, tileLocation);

            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            player.SendSuccessMessage(
              string.Format("This {0} is not protected anymore.", TerrariaUtils.Tiles.GetBlockTypeName(blockType))
            );

            return true;
              } catch (InvalidBlockTypeException ex) {
            if (sendFailureMessages) {
              string messageFormat;
              if (TerrariaUtils.Tiles.IsSolidBlockType(ex.BlockType, true))
            messageFormat = "Deprotecting {0} blocks is not allowed.";
              else
            messageFormat = "Deprotecting {0} objects is not allowed.";

              player.SendErrorMessage(string.Format(messageFormat, TerrariaUtils.Tiles.GetBlockTypeName(ex.BlockType)));
            }

            return false;
              } catch (NoProtectionException) {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            if (sendFailureMessages) {
              player.SendErrorMessage(string.Format(
            "This {0} is not protected by Protector at all.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
              ));
            }

            return false;
              } catch (TileProtectedException) {
            BlockType blockType = (BlockType)TerrariaUtils.Tiles[tileLocation].type;
            player.SendErrorMessage(string.Format(
              "This {0} is owned by someone else, you can't deprotect it.", TerrariaUtils.Tiles.GetBlockTypeName(blockType)
            ));

            return false;
              }
        }
Ejemplo n.º 18
0
        private void AddReport(User reported, TSPlayer reportee, string message)
        {
            var success =
                Db.Query("INSERT INTO Reports (UserID, ReportedID, Message, Position, State) VALUES "
                         + " (@0, @1, @2, @3, @4)",
                    reportee.User.ID, reported.ID, message,
                    reportee.TPlayer.position.X + ":" + reportee.TPlayer.position.Y, 0) > 0;

            int id = 0;

            using (var reader = Db.QueryReader("SELECT MAX(ReportID) AS ReportID FROM Reports"))
            {
                if (reader.Read())
                {
                    id = reader.Get<int>("ReportID");
                }
            }

            if (success)
            {
                reportee.SendSuccessMessage("Successfully reported {0}.", reported.Name);
                reportee.SendSuccessMessage("Reason: {0}", message);
                reportee.SendSuccessMessage("Position: ({0},{1})", (int)reportee.TPlayer.position.X, (int)reportee.TPlayer.position.Y);
                TShock.Players.Where(p => p != null && p.ConnectionAlive && p.RealPlayer)
                    .ForEach(p =>
                    {
                        if (p.Group.HasPermission("reports.report.check"))
                        {
                            p.SendWarningMessage("{0} has reported {1}. Use /creports {2} to view it.",
                                reportee.Name, reported.Name, id);
                        }
                    });
            }
            else
            {
                reportee.SendErrorMessage("Report was not successful. Please check logs for details");
            }
        }
        public bool TrySetUpBankChest(TSPlayer player, DPoint tileLocation, int bankChestIndex, bool sendMessages = true)
        {
            if (!player.IsLoggedIn) {
            if (sendMessages)
              player.SendErrorMessage("You have to be logged in in order to set up bank chests.");

            return false;
              }

              if (!this.ProtectionManager.CheckBlockAccess(player, tileLocation, true) && !player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission)) {
            player.SendErrorMessage("You don't own the protection of this chest.");
            return false;
              }

              try {
            this.ChestManager.SetUpBankChest(player, tileLocation, bankChestIndex, true);

            player.SendSuccessMessage(string.Format(
              $"This chest is now an instance of your bank chest with the number {TShock.Utils.ColorTag(bankChestIndex.ToString(), Color.Red)}."
            ));

            return true;
              } catch (ArgumentException ex) {
            if (ex.ParamName == "tileLocation") {
              if (sendMessages)
            player.SendErrorMessage("There is no chest here.");

              return false;
            } else if (ex.ParamName == "bankChestIndex") {
              ArgumentOutOfRangeException actualEx = (ArgumentOutOfRangeException)ex;
              if (sendMessages) {
            string messageFormat;
            if (!player.Group.HasPermission(ProtectorPlugin.NoBankChestLimits_Permision))
              messageFormat = "The bank chest number must be between 1 and {0}.";
            else
              messageFormat = "The bank chest number must be greater than 1.";

            player.SendErrorMessage(string.Format(messageFormat, actualEx.ActualValue));
              }

              return false;
            }

            throw;
              } catch (MissingPermissionException) {
            if (sendMessages)
              player.SendErrorMessage("You are not allowed to define bank chests.");

            return false;
              } catch (InvalidBlockTypeException) {
            if (sendMessages)
              player.SendErrorMessage("Only chests can be converted to bank chests.");

            return false;
              } catch (NoProtectionException) {
            if (sendMessages)
              player.SendErrorMessage("The chest needs to be protected to be converted to a bank chest.");

            return false;
              } catch (ChestNotEmptyException) {
            if (sendMessages)
              player.SendErrorMessage("The chest has to be empty in order to restore a bank chest here.");

            return false;
              } catch (ChestTypeAlreadyDefinedException) {
            if (sendMessages)
              player.SendErrorMessage("The chest is already a bank chest.");

            return false;
              } catch (ChestIncompatibilityException) {
            if (sendMessages)
              player.SendErrorMessage("A bank chest can not be a refill- or trade chest at the same time.");

            return false;
              } catch (NoChestDataException) {
            if (sendMessages) {
              player.SendErrorMessage("Error: There are no chest data for this chest available. This world's data might be");
              player.SendErrorMessage("corrupted.");
            }

            return false;
              } catch (BankChestAlreadyInstancedException) {
            if (sendMessages) {
              player.SendErrorMessage(string.Format("There is already an instance of your bank chest with the index {0} in", bankChestIndex));
              player.SendErrorMessage("this world.");
            }

            return false;
              }
        }
        // Called after (probably) all other plugin's tile edit handlers.
        public virtual bool HandlePostTileEdit(
            TSPlayer player, TileEditType editType, BlockType blockType, DPoint location, int objectStyle
            )
        {
            if (this.IsDisposed || editType != TileEditType.PlaceTile)
            return false;
              if (!this.Config.AutoProtectedTiles[(int)blockType])
            return false;

              Task.Factory.StartNew(() => {
            Thread.Sleep(150);

            Tile tile = TerrariaUtils.Tiles[location];
            if (!tile.active())
              return;

            try {
              this.ProtectionManager.CreateProtection(player, location, false);

              if (this.Config.NotifyAutoProtections)
            player.SendSuccessMessage(string.Format("This {0} has been protected.", TerrariaUtils.Tiles.GetBlockTypeName((BlockType)tile.type)));
            } catch (PlayerNotLoggedInException) {
              player.SendWarningMessage(string.Format(
            "This {0} will not be protected because you're not logged in.", TerrariaUtils.Tiles.GetBlockTypeName((BlockType)tile.type)
              ));
            } catch (LimitEnforcementException) {
              player.SendWarningMessage(string.Format(
            "This {0} will not be protected because you've reached the protection limit.", TerrariaUtils.Tiles.GetBlockTypeName((BlockType)tile.type)
              ));
            } catch (TileProtectedException) {
              this.PluginTrace.WriteLineError("Error: A block was tried to be auto protected where tile placement should not be possible.");
            } catch (AlreadyProtectedException) {
              this.PluginTrace.WriteLineError("Error: A block was tried to be auto protected on the same position of an existing protection.");
            } catch (Exception ex) {
              this.PluginTrace.WriteLineError("Unexpected exception was thrown during auto protection setup: \n" + ex);
            }
              }, TaskCreationOptions.PreferFairness);

              return false;
        }
Ejemplo n.º 21
0
        public static void SendPage(
            TSPlayer player, int pageNumber, IEnumerable dataToPaginate, int dataToPaginateCount, Settings settings = null)
        {
            if (settings == null)
            {
                settings = new Settings();
            }

            if (dataToPaginateCount == 0)
            {
                if (settings.NothingToDisplayString != null)
                {
                    if (!player.RealPlayer)
                    {
                        player.SendSuccessMessage(settings.NothingToDisplayString);
                    }
                    else
                    {
                        player.SendMessage(settings.NothingToDisplayString, settings.HeaderTextColor);
                    }
                }
                return;
            }

            int pageCount = ((dataToPaginateCount - 1) / settings.MaxLinesPerPage) + 1;

            if (settings.PageLimit > 0 && pageCount > settings.PageLimit)
            {
                pageCount = settings.PageLimit;
            }
            if (pageNumber > pageCount)
            {
                pageNumber = pageCount;
            }

            if (settings.IncludeHeader)
            {
                if (!player.RealPlayer)
                {
                    player.SendSuccessMessage(string.Format(settings.HeaderFormat, pageNumber, pageCount));
                }
                else
                {
                    player.SendMessage(string.Format(settings.HeaderFormat, pageNumber, pageCount), settings.HeaderTextColor);
                }
            }

            int listOffset    = (pageNumber - 1) * settings.MaxLinesPerPage;
            int offsetCounter = 0;
            int lineCounter   = 0;

            foreach (object lineData in dataToPaginate)
            {
                if (lineData == null)
                {
                    continue;
                }
                if (offsetCounter++ < listOffset)
                {
                    continue;
                }
                if (lineCounter++ == settings.MaxLinesPerPage)
                {
                    break;
                }

                string lineMessage;
                Color  lineColor = settings.LineTextColor;
                if (lineData is Tuple <string, Color> )
                {
                    var lineFormat = (Tuple <string, Color>)lineData;
                    lineMessage = lineFormat.Item1;
                    lineColor   = lineFormat.Item2;
                }
                else if (settings.LineFormatter != null)
                {
                    try
                    {
                        Tuple <string, Color> lineFormat = settings.LineFormatter(lineData, offsetCounter, pageNumber);
                        if (lineFormat == null)
                        {
                            continue;
                        }

                        lineMessage = lineFormat.Item1;
                        lineColor   = lineFormat.Item2;
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidOperationException(
                                  "The method referenced by LineFormatter has thrown an exception. See inner exception for details.", ex);
                    }
                }
                else
                {
                    lineMessage = lineData.ToString();
                }

                if (lineMessage != null)
                {
                    if (!player.RealPlayer)
                    {
                        player.SendInfoMessage(lineMessage);
                    }
                    else
                    {
                        player.SendMessage(lineMessage, lineColor);
                    }
                }
            }

            if (lineCounter == 0)
            {
                if (settings.NothingToDisplayString != null)
                {
                    if (!player.RealPlayer)
                    {
                        player.SendSuccessMessage(settings.NothingToDisplayString);
                    }
                    else
                    {
                        player.SendMessage(settings.NothingToDisplayString, settings.HeaderTextColor);
                    }
                }
            }
            else if (settings.IncludeFooter && pageNumber + 1 <= pageCount)
            {
                if (!player.RealPlayer)
                {
                    player.SendInfoMessage(string.Format(settings.FooterFormat, pageNumber + 1, pageNumber, pageCount));
                }
                else
                {
                    player.SendMessage(string.Format(settings.FooterFormat, pageNumber + 1, pageNumber, pageCount), settings.FooterTextColor);
                }
            }
        }
        /// <exception cref="FormatException">The format item in <paramref name="format" /> is invalid.-or- The index of a format item is not zero. </exception>
        public bool TrySetUpRefillChest(
            TSPlayer player, DPoint tileLocation, TimeSpan? refillTime, bool? oneLootPerPlayer, int? lootLimit, bool? autoLock,
            bool? autoEmpty, bool sendMessages = true
            )
        {
            if (!player.IsLoggedIn) {
            if (sendMessages)
              player.SendErrorMessage("You have to be logged in in order to set up refill chests.");

            return false;
              }

              if (!this.ProtectionManager.CheckBlockAccess(player, tileLocation, true) && !player.Group.HasPermission(ProtectorPlugin.ProtectionMaster_Permission)) {
            player.SendErrorMessage("You don't own the protection of this chest.");
            return false;
              }

              try {
            if (this.ChestManager.SetUpRefillChest(
              player, tileLocation, refillTime, oneLootPerPlayer, lootLimit, autoLock, autoEmpty, false, true
            )) {
              if (sendMessages) {
            player.SendSuccessMessage("Refill chest successfully set up.");

            if (this.Config.AllowRefillChestContentChanges)
              player.SendSuccessMessage("As you are the owner of it, you may still freely modify its contents.");
              }
            } else {
              if (sendMessages) {
            if (refillTime != null) {
              if (refillTime != TimeSpan.Zero)
                player.SendSuccessMessage($"Set the refill timer of this chest to {refillTime.Value.ToLongString()}.");
              else
                player.SendSuccessMessage("This chest will now refill instantly.");
            }
            if (oneLootPerPlayer != null) {
              if (oneLootPerPlayer.Value)
                player.SendSuccessMessage("This chest can now be looted one single time by each player.");
              else
                player.SendSuccessMessage("This chest can now be looted freely.");
            }
            if (lootLimit != null) {
              if (lootLimit.Value != -1)
                player.SendSuccessMessage($"This chest can now be looted only {lootLimit} more times.");
              else
                player.SendSuccessMessage("This chest can now be looted endlessly.");
            }
            if (autoLock != null) {
              if (autoLock.Value)
                player.SendSuccessMessage("This chest locks itself automatically when it gets looted.");
              else
                player.SendSuccessMessage("This chest will not lock itself automatically anymore.");
            }
            if (autoEmpty != null) {
              if (autoEmpty.Value)
                player.SendSuccessMessage("This chest empties itself automatically when it gets looted.");
              else
                player.SendSuccessMessage("This chest will not empty itself automatically anymore.");
            }
              }
            }

            if (this.Config.AutoShareRefillChests) {
              foreach (ProtectionEntry protection in this.ProtectionManager.EnumerateProtectionEntries(tileLocation)) {
            protection.IsSharedWithEveryone = true;
            break;
              }
            }

            return true;
              } catch (ArgumentException ex) {
            if (ex.ParamName == "tileLocation") {
              if (sendMessages)
            player.SendErrorMessage("There is no chest here.");

              return false;
            }

            throw;
              } catch (MissingPermissionException) {
            if (sendMessages)
              player.SendErrorMessage("You are not allowed to define refill chests.");

            return false;
              } catch (NoProtectionException) {
            if (sendMessages)
              player.SendErrorMessage("The chest needs to be protected to be converted to a refill chest.");

            return false;
              } catch (ChestIncompatibilityException) {
            if (sendMessages)
              player.SendErrorMessage("A chest can not be a refill- and bank chest at the same time.");

            return false;
              } catch (NoChestDataException) {
            if (sendMessages) {
              player.SendErrorMessage("Error: There are no chest data for this chest available. This world's data might be");
              player.SendErrorMessage("corrupted.");
            }

            return false;
              }
        }