Example #1
0
        /// <summary>
        /// Asynchronously transfers to another account.
        /// </summary>
        public Task <BankTransferEventArgs> TransferToAsync(int Index, Money Amount, BankAccountTransferOptions Options, string Message = "")
        {
            Economy.EconomyPlayer ePlayer = SEconomyPlugin.GetEconomyPlayerSafe(Index);

            Guid profile = SEconomyPlugin.Profiler.Enter(string.Format("transferAsync: {0} to {1}", this.UserAccountName, ePlayer.BankAccount != null ? ePlayer.BankAccount.UserAccountName : "Unknown"));

            return(Task.Factory.StartNew <BankTransferEventArgs>(() => {
                BankTransferEventArgs args = TransferTo(ePlayer.BankAccount, Amount, Options, UseProfiler: false, Message: Message);
                return args;
            }).ContinueWith((task) => {
                SEconomyPlugin.Profiler.ExitLog(profile);
                return task.Result;
            }));
        }
        /// <summary>
        /// This is a copy of TShocks handlecommand method, sans the permission checks
        /// </summary>
        public static bool HandleCommandWithoutPermissions(TShockAPI.TSPlayer player, string text)
        {
            string cmdText = text.Remove(0, 1);
            var    args    = SEconomyPlugin.CallPrivateMethod <List <string> >(typeof(TShockAPI.Commands), true, "ParseParameters", cmdText);

            if (args.Count < 1)
            {
                return(false);
            }

            string cmdName = args[0].ToLower();

            args.RemoveAt(0);

            IEnumerable <TShockAPI.Command> cmds = TShockAPI.Commands.ChatCommands.Where(c => c.HasAlias(cmdName));

            if (Enumerable.Count(cmds) == 0)
            {
                if (player.AwaitingResponse.ContainsKey(cmdName))
                {
                    Action <TShockAPI.CommandArgs> call = player.AwaitingResponse[cmdName];
                    player.AwaitingResponse.Remove(cmdName);
                    call(new TShockAPI.CommandArgs(cmdText, player, args));
                    return(true);
                }
                player.SendErrorMessage("Invalid command entered. Type /help for a list of valid commands.");
                return(true);
            }
            foreach (TShockAPI.Command cmd in cmds)
            {
                if (!cmd.AllowServer && !player.RealPlayer)
                {
                    player.SendErrorMessage("You must use this command in-game.");
                }
                else
                {
                    if (cmd.DoLog)
                    {
                        TShockAPI.TShock.Utils.SendLogs(string.Format("{0} executed: /{1}.", player.Name, cmdText), Color.Red);
                    }
                    cmd.RunWithoutPermissions(cmdText, player, args);
                }
            }
            return(true);
        }
Example #3
0
 public void EndTrivia(CommandArgs args, bool CorrectAnswer)
 {
     if (!CorrectAnswer)
     {
         TSPlayer.All.SendErrorMessage("[Trivia] Time is up!");
         return;
     }
     else
     {
         TSPlayer.All.SendInfoMessage(string.Format("{0} answered the trivia correctly! the answer was: {1}", args.Player.Name, T.Answer.Replace(',', '/')));
         if (config.DisplayWrongAnswers && WrongAnswers.Count > 0)
         {
             TSPlayer.All.SendErrorMessage(string.Format("Wrong answers were: {0}", string.Join(", ", WrongAnswers)));
         }
         if (config.GiveSEconomyCurrency)
         {
             Wolfje.Plugins.SEconomy.Economy.EconomyPlayer Server = SEconomyPlugin.GetEconomyPlayerSafe(TShockAPI.TSServerPlayer.Server.UserID);
             Server.BankAccount.TransferToAsync(args.Player.Index, config.CurrencyAmount, Wolfje.Plugins.SEconomy.Journal.BankAccountTransferOptions.AnnounceToReceiver, "answering the trivia question correctly", "Answered trivia question");
         }
     }
     seconds  = 0;
     T.Answer = ""; T.Question = "";
     WrongAnswers.Clear();
 }
Example #4
0
        /// <summary>
        /// Occurs when someone executes an alias command
        /// </summary>
        void ChatCommand_AliasExecuted(TShockAPI.CommandArgs e)
        {
            string commandIdentifier = e.Message;

            if (!string.IsNullOrEmpty(e.Message))
            {
                commandIdentifier = e.Message.Split(' ').FirstOrDefault();
            }

            //Get the corresponding alias in the config that matches what the user typed.
            foreach (AliasCommand alias in Configuration.CommandAliases.Where(i => i.CommandAlias == commandIdentifier))
            {
                if (alias != null)
                {
                    TimeSpan timeSinceLastUsedCommand = TimeSpan.MaxValue;
                    //cooldown key is a pair of the user's character name, and the command they have called.
                    //cooldown value is a DateTime they last used the command.
                    KeyValuePair <string, AliasCommand> cooldownReference = new KeyValuePair <string, AliasCommand>(e.Player.Name, alias);

                    if (CooldownList.ContainsKey(cooldownReference))
                    {
                        //UTC time so we don't get any daylight saving shit cuntery
                        timeSinceLastUsedCommand = DateTime.UtcNow.Subtract(CooldownList[cooldownReference]);
                    }

                    //has the time elapsed greater than the cooldown period?
                    if (timeSinceLastUsedCommand.TotalSeconds >= alias.CooldownSeconds || e.Player.Group.HasPermission("aliascmd.bypasscooldown"))
                    {
                        Money commandCost             = 0;
                        Economy.EconomyPlayer ePlayer = SEconomyPlugin.GetEconomyPlayerSafe(e.Player.Index);

                        if (!string.IsNullOrEmpty(alias.Cost) && Money.TryParse(alias.Cost, out commandCost) && !e.Player.Group.HasPermission("aliascmd.bypasscost"))
                        {
                            if (ePlayer.BankAccount != null)
                            {
                                if (!ePlayer.BankAccount.IsAccountEnabled)
                                {
                                    e.Player.SendErrorMessageFormat("You cannot use this command because your account is disabled.");
                                }
                                else if (ePlayer.BankAccount.Balance >= commandCost)
                                {
                                    //Take money off the player, and indicate that this is a payment for something tangible.
                                    Journal.BankTransferEventArgs trans = SEconomyPlugin.WorldAccount.TransferTo(ePlayer.BankAccount, -commandCost, Journal.BankAccountTransferOptions.AnnounceToReceiver | Journal.BankAccountTransferOptions.IsPayment);
                                    if (trans.TransferSucceeded)
                                    {
                                        DoCommands(alias, ePlayer.TSPlayer, e.Parameters);
                                    }
                                    else
                                    {
                                        e.Player.SendErrorMessageFormat("Your payment failed.");
                                    }
                                }
                                else
                                {
                                    e.Player.SendErrorMessageFormat("This command costs {0}. You need {1} more to be able to use this.", commandCost.ToLongString(), ((Money)(ePlayer.BankAccount.Balance - commandCost)).ToLongString());
                                }
                            }
                            else
                            {
                                e.Player.SendErrorMessageFormat("This command costs money and you don't have a bank account.  Please log in first.");
                            }
                        }
                        else
                        {
                            //Command is free
                            DoCommands(alias, e.Player, e.Parameters);
                        }

                        //populate the cooldown list.  This dictionary does not go away when people leave so they can't
                        //reset cooldowns by simply logging out or disconnecting.  They can reset it however by logging into
                        //a different account.
                        if (CooldownList.ContainsKey(cooldownReference))
                        {
                            CooldownList[cooldownReference] = DateTime.UtcNow;
                        }
                        else
                        {
                            CooldownList.Add(cooldownReference, DateTime.UtcNow);
                        }
                    }
                    else
                    {
                        e.Player.SendErrorMessageFormat("{0}: You need to wait {1:0} more seconds to be able to use that.", alias.CommandAlias, (alias.CooldownSeconds - timeSinceLastUsedCommand.TotalSeconds));
                    }
                }
            }
        }
Example #5
0
        /// <summary>
        /// Executes the AliasCommand.  Will either forward the command to the tshock handler or do something else
        /// </summary>
        void DoCommands(AliasCommand alias, TShockAPI.TSPlayer player, List <string> parameters)
        {
            //loop through each alias and do the commands.
            foreach (string commandToExecute in alias.CommandsToExecute)
            {
                //todo: parse paramaters and dynamics
                string mangledString = commandToExecute;

                //specifies whether the command to run should be executed as a command, or ignored.
                //useful for functions like $msg that does other shit
                bool executeCommand = true;

                //replace parameter markers with actual parameter values
                ReplaceParameterMarkers(parameters, ref mangledString);

                mangledString = mangledString.Replace("$calleraccount", player.UserAccountName);
                mangledString = mangledString.Replace("$callername", player.Name);

                //$random(x,y) support.  Returns a random number between x and y

                if (randomRegex.IsMatch(mangledString))
                {
                    foreach (Match match in randomRegex.Matches(mangledString))
                    {
                        int randomFrom = 0;
                        int randomTo   = 0;

                        if (!string.IsNullOrEmpty(match.Groups[2].Value) && int.TryParse(match.Groups[2].Value, out randomTo) &&
                            !string.IsNullOrEmpty(match.Groups[1].Value) && int.TryParse(match.Groups[1].Value, out randomFrom))
                        {
                            Random random = new Random();

                            mangledString = mangledString.Replace(match.ToString(), random.Next(randomFrom, randomTo).ToString());
                        }
                        else
                        {
                            TShockAPI.Log.ConsoleError(match.ToString() + " has some stupid shit in it, have a look at your AliasCmd config file.");
                            mangledString = mangledString.Replace(match.ToString(), "");
                        }
                    }
                }

                // $runas(u,cmd) support.  Run command as user
                if (runasFunctionRegex.IsMatch(mangledString))
                {
                    foreach (Match match in runasFunctionRegex.Matches(mangledString))
                    {
                        string impersonatedName = match.Groups[2].Value;
                        Economy.EconomyPlayer impersonatedPlayer = SEconomyPlugin.GetEconomyPlayerSafe(impersonatedName);

                        if (impersonatedPlayer != null)
                        {
                            string commandToRun = match.Groups[3].Value;;
                            player = impersonatedPlayer.TSPlayer;

                            mangledString = commandToRun.Trim();
                        }
                    }
                }

                // $msg(u,msg) support.  Sends the user a non-chat informational message
                if (msgRegex.IsMatch(mangledString))
                {
                    foreach (Match match in msgRegex.Matches(mangledString))
                    {
                        string msgTarget = match.Groups[2].Value.Trim();
                        string message   = match.Groups[3].Value.Trim();
                        Economy.EconomyPlayer destinationPlayer = SEconomyPlugin.GetEconomyPlayerSafe(msgTarget);

                        if (destinationPlayer != null)
                        {
                            //custom command, skip forwarding of the command to the tshock executer
                            executeCommand = false;

                            destinationPlayer.TSPlayer.SendInfoMessage(message);
                        }
                    }
                }


                //and send the command to tshock to do.
                try {
                    //prevent an infinite loop for a subcommand calling the alias again causing a commandloop
                    string command = mangledString.Split(' ')[0].Substring(1);
                    if (!command.Equals(alias.CommandAlias, StringComparison.CurrentCultureIgnoreCase))
                    {
                        if (executeCommand)
                        {
                            HandleCommandWithoutPermissions(player, mangledString);
                        }
                    }
                    else
                    {
                        TShockAPI.Log.ConsoleError(string.Format("cmdalias {0}: calling yourself in an alias will cause an infinite loop. Ignoring.", alias.CommandAlias));
                    }
                } catch {
                    //execute the command disregarding permissions
                    player.SendErrorMessage(alias.UsageHelpText);
                }
            }
        }
Example #6
0
        /// <summary>
        /// Transfers money from this player to the destination account.  If negative, takes money from the destionation account into this account.
        /// </summary>
        public BankTransferEventArgs TransferTo(int Index, Money Amount, Journal.BankAccountTransferOptions Options, string Message = "")
        {
            Economy.EconomyPlayer ePlayer = SEconomyPlugin.GetEconomyPlayerSafe(Index);

            return(TransferTo(ePlayer.BankAccount, Amount, Options, Message: Message));
        }
Example #7
0
        internal static void Initialize()
        {
            CmdAliasPlugin.scriptEngine = new Jint.JintEngine();
            CmdAliasPlugin.scriptEngine.DisableSecurity();
            CmdAliasPlugin.scriptEngine.SetDebugMode(true);

            ///function seconomy_transfer_async(toAccount : Journal.XBankAccount, player : TShockAPI.TSPlayer, amount : string, completedCallback : function)
            ///
            ///Asynchronously transfers money using SEconomy, then calls back to the JS function specified by completedCallback
            CmdAliasPlugin.scriptEngine.SetFunction("seconomy_transfer_async", new TransferAsyncDelegate((from, to, amount, msg, func) => {
                from.TransferToAsync(to, amount, Journal.BankAccountTransferOptions.AnnounceToSender, Message: msg).ContinueWith((task) => {
                    //callback to the JS function with the result of the transfer
                    CmdAliasPlugin.scriptEngine.CallFunction(func, task.Result);
                });
            }));

            CmdAliasPlugin.scriptEngine.SetFunction("seconomy_pay_async", new TransferAsyncDelegate((from, to, amount, msg, func) => {
                from.TransferToAsync(to, amount, Journal.BankAccountTransferOptions.AnnounceToReceiver | Journal.BankAccountTransferOptions.AnnounceToSender | Journal.BankAccountTransferOptions.IsPayment, Message: msg).ContinueWith((task) => {
                    //callback to the JS function with the result of the transfer
                    CmdAliasPlugin.scriptEngine.CallFunction(func, task.Result);
                });
            }));

            CmdAliasPlugin.scriptEngine.SetFunction("seconomy_parse_money", new Func <object, Money>((moneyString) => {
                return(Money.Parse(moneyString.ToString()));
            }));


            CmdAliasPlugin.scriptEngine.SetFunction("seconomy_get_account", new Func <object, Journal.XBankAccount>((accountName) => {
                if (accountName is TShockAPI.TSPlayer)
                {
                    return(SEconomyPlugin.GetEconomyPlayerSafe((accountName as TShockAPI.TSPlayer).Name).BankAccount);
                }
                else
                {
                    return(SEconomyPlugin.GetEconomyPlayerSafe(accountName.ToString()).BankAccount);
                }
            }));


            ///global variable: __world_account
            ///
            ///Returns a reference to the SEconomy world account
            CmdAliasPlugin.scriptEngine.SetFunction("seconomy_world_account", new Func <Journal.XBankAccount>(() => {
                return(SEconomyPlugin.WorldAccount);
            }));

            ///function create_alias(aliasName : string, commandCost : string, cooldownSeconds : integer, permissionsNeeded : string, functionToExecute : function)
            ///
            ///Creates an alias that executes the specified functionToExecute in js when it is called by a player/server.
            CmdAliasPlugin.scriptEngine.SetFunction("create_alias", new RegisterCommandDelegate((aliasname, cost, cooldown, perms, func) => {
                JScriptAliasCommand jAlias = new JScriptAliasCommand()
                {
                    CommandAlias = aliasname, CooldownSeconds = Convert.ToInt32(cooldown), Cost = cost, Permissions = perms, func = func
                };

                jsAliases.RemoveAll(i => i.CommandAlias == aliasname);
                jsAliases.Add(jAlias);
            }));

            /// function log(logEntry : string)
            ///
            ///Writes logEntry to the TShock log
            CmdAliasPlugin.scriptEngine.SetFunction <string>("log", (logText) => {
                TShockAPI.Log.ConsoleInfo(logText);
            });

            ///function get_player(playerName : string) : TShockAPI.TSPlayer
            ///
            ///Returns a TSPlayer by their characterName.  Returns undefined if the player isn't found or is offline.
            CmdAliasPlugin.scriptEngine.SetFunction("get_player", new Func <string, TShockAPI.TSPlayer>((name) => {
                return(TShockAPI.TShock.Players.FirstOrDefault(i => i.Name == name));
            }));

            ///function random(from : integer, to : integer) : integer
            ///
            ///Returns a random number between from and to.
            CmdAliasPlugin.scriptEngine.SetFunction("random", new Func <double, double, double>((rndFrom, rndTo) => {
                lock (__rndLock) {
                    int from = Convert.ToInt32(rndFrom);
                    int to   = Convert.ToInt32(rndTo);
                    return(randomGenerator.Next(from, to));
                }
            }));

            //function group_exists(groupName : string) : boolean
            //
            //Returns whether the TShock group specified by groupName exists
            CmdAliasPlugin.scriptEngine.SetFunction("group_exists", new Func <object, bool>((groupName) => {
                return(TShockAPI.TShock.Groups.Count(i => i.Name.Equals(groupName.ToString(), StringComparison.CurrentCultureIgnoreCase)) > 0);
            }));

            //tshock_group(groupName : string) : TShockAPI.Group
            //
            //Returns a TShock Group object by its name
            CmdAliasPlugin.scriptEngine.SetFunction("tshock_group", new Func <object, TShockAPI.Group>((groupName) => {
                if (groupName == null)
                {
                    return(null);
                }

                TShockAPI.Group g = TShockAPI.TShock.Groups.FirstOrDefault(i => i.Name.Equals(groupName.ToString(), StringComparison.CurrentCultureIgnoreCase));
                return(g);
            }));

            //function execute_command(player : TShockAPI.TSPlayer, command : string)
            //
            //causes player to execute provided command in the TShock execution handler.
            //this function ignores permissions, and will always execute as though the user has permissions to do it.
            CmdAliasPlugin.scriptEngine.SetFunction("execute_command", new Action <TShockAPI.TSPlayer, object>((player, cmd) => {
                string commandToExecute = "";
                if (cmd is List <string> )
                {
                    List <string> cmdList = cmd as List <string>;

                    foreach (var param in cmdList.Skip(1))
                    {
                        commandToExecute += " " + param;
                    }
                }
                else if (cmd is string)
                {
                    commandToExecute = cmd.ToString();
                }

                CmdAliasPlugin.HandleCommandWithoutPermissions(player, string.Format("{0}", commandToExecute.Trim()));
            }));

            //function change_group(player : TShockAPI.TSPlayer, groupName : string)
            //
            //Changes the player's TShock group to the group provided by groupName
            CmdAliasPlugin.scriptEngine.SetFunction("change_group", new Action <TShockAPI.TSPlayer, object>((player, group) => {
                TShockAPI.DB.User u = new TShockAPI.DB.User();
                string g            = "";

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

                if (player != null && !string.IsNullOrEmpty(g))
                {
                    u.Name = player.UserAccountName;
                    TShockAPI.TShock.Users.SetUserGroup(u, g);
                }
            }));

            ///function msg(player : TShockAPI.TSPlayer, message : string)
            ///
            ///Sends an informational message to a player.
            CmdAliasPlugin.scriptEngine.SetFunction("msg", new Action <TShockAPI.TSPlayer, object>((player, msg) => {
                if (player != null && msg != null)
                {
                    player.SendInfoMessageFormat("{0}", msg);
                }
            }));

            ///function broadcast(msg : string)
            ///
            ///Sends a server broadcast.
            CmdAliasPlugin.scriptEngine.SetFunction("broadcast", new Action <object>((msg) => {
                if (msg != null)
                {
                    TShockAPI.TShock.Utils.Broadcast("(Server Broadcast) " + msg.ToString(), Color.Red);
                }
            }));
        }
Example #8
0
        /// <summary>
        /// Occurs when the server sends data.
        /// </summary>
        void NetHooks_SendData(Hooks.SendDataEventArgs e)
        {
            if (e.MsgID == PacketTypes.NpcStrike)
            {
                NPC npc = Main.npc[e.number];

                if (npc != null)
                {
                    if (npc.boss)
                    {
                        if (npc.life <= 0)
                        {
                            for (int i = BossList.Count - 1; i >= 0; i--)
                            {
                                if (BossList[i].Npc == null)
                                {
                                    BossList.RemoveAt(i);
                                }
                                else if (BossList[i].Npc == npc)
                                {
                                    var rewardDict = BossList[i].GetRecalculatedReward();

                                    foreach (KeyValuePair <int, long> reward in rewardDict)
                                    {
                                        if (PlayerList[reward.Key] != null)
                                        {
                                            SEconomy.Economy.EconomyPlayer ePlayer = SEconomyPlugin.GetEconomyPlayerSafe(reward.Key);
                                            if (ePlayer != null)
                                            {
                                                //Pay from the world account to the reward recipient.
                                                Journal.BankAccountTransferOptions options = Journal.BankAccountTransferOptions.None;

                                                if (Config.AnnounceBossGain)
                                                {
                                                    options |= Journal.BankAccountTransferOptions.AnnounceToReceiver;
                                                }

                                                SEconomyPlugin.WorldAccount.TransferTo(ePlayer.BankAccount, reward.Value, options);
                                            }
                                        }
                                    }
                                    BossList.RemoveAt(i);
                                }
                                else if (!BossList[i].Npc.active)
                                {
                                    BossList.RemoveAt(i);
                                }
                            }

                            if (e.ignoreClient >= 0)
                            {
                                var player = PlayerList[e.ignoreClient];
                                if (player != null)
                                {
                                    player.AddKill(npc.netID);
                                }
                            }
                        }
                        else if (e.ignoreClient >= 0)
                        {
                            var bossnpc = BossList.Find(n => n.Npc == npc);
                            if (bossnpc != null)
                            {
                                bossnpc.AddDamage(e.ignoreClient, (int)e.number2);
                            }
                            else
                            {
                                BossNPC newBoss = new BossNPC(npc);
                                newBoss.AddDamage(e.ignoreClient, (int)e.number2);
                                BossList.Add(newBoss);
                            }
                        }
                    }
                    else if (npc.life <= 0 && e.ignoreClient >= 0)
                    {
                        var player = PlayerList[e.ignoreClient];
                        if (player != null)
                        {
                            if (npc.value > 0)
                            {
                                float Mod = 1;
                                if (player.TSPlayer.TPlayer.buffType.Contains(13))   // battle potion
                                {
                                    Mod *= Config.BattlePotionModifier;
                                }
                                if (Config.OptionalMobModifier.ContainsKey(npc.netID))
                                {
                                    Mod *= Config.OptionalMobModifier[npc.netID]; // apply custom modifiers
                                }


                                int minVal    = (int)((npc.value - (npc.value * 0.1)) * Mod);
                                int maxVal    = (int)((npc.value + (npc.value * 0.1)) * Mod);
                                int rewardAmt = _r.Next(minVal, maxVal);

                                int i = player.TSPlayer.Index;

                                SEconomy.Economy.EconomyPlayer     epl     = SEconomyPlugin.GetEconomyPlayerSafe(i);
                                Journal.BankAccountTransferOptions options = Journal.BankAccountTransferOptions.None;

                                if (Config.AnnounceKillGain)
                                {
                                    options |= Journal.BankAccountTransferOptions.AnnounceToReceiver;
                                }

                                SEconomyPlugin.WorldAccount.TransferTo(i, rewardAmt, options);
                            }
                            player.AddKill(npc.netID);
                        }
                    }
                }
            }
            else if (e.MsgID == PacketTypes.PlayerKillMe)
            {
                //Console.WriteLine("(SendData) PlayerKillMe -> 1:{0} 2:{4} 3:{5} 4:{6} 5:{1} remote:{2} ignore:{3}", e.number, e.number5, e.remoteClient, e.ignoreClient, e.number2, e.number3, e.number4);
                // 1-playerID, 2-direction, 3-dmg, 4-PVP
                var deadPlayer = PlayerList[e.number];
                Economy.EconomyPlayer eDeadPlayer = SEconomyPlugin.GetEconomyPlayerSafe(e.number);

                if (deadPlayer != null)
                {
                    long penaltyAmmount = 0;

                    if (Config.StaticDeathPenalty)
                    {
                        penaltyAmmount = _r.Next(Config.DeathPenaltyMin, Config.DeathPenaltyMax);
                    }
                    else if (eDeadPlayer.BankAccount != null)
                    {
                        penaltyAmmount = (long)(eDeadPlayer.BankAccount.Balance * (Config.DeathPenaltyPercent / 100f));
                    }

                    //   Console.WriteLine("penalty ammount: {0}", penaltyAmmount);
                    if (e.number4 == 1)
                    {
                        if (!deadPlayer.TSPlayer.Group.HasPermission("vault.bypass.death") /* && deadPlayer.ChangeMoney(-penaltyAmmount, MoneyEventFlags.PvP, true) */ && Config.PvPWinnerTakesLoosersPenalty && deadPlayer.LastPVPID != -1)
                        {
                            var killer = PlayerList[deadPlayer.LastPVPID];
                            Economy.EconomyPlayer eKiller = SEconomyPlugin.GetEconomyPlayerSafe(deadPlayer.LastPVPID);

                            if (eKiller != null && eKiller.BankAccount != null)
                            {
                                Journal.BankAccountTransferOptions options = Journal.BankAccountTransferOptions.MoneyFromPvP | Journal.BankAccountTransferOptions.AnnounceToReceiver | Journal.BankAccountTransferOptions.AnnounceToSender;

                                //  killer.ChangeMoney(penaltyAmmount, MoneyEventFlags.PvP, true);

                                //Here in PVP the loser pays the winner money out of their account.
                                eDeadPlayer.BankAccount.TransferTo(deadPlayer.LastPVPID, penaltyAmmount, options);
                            }
                        }
                    }
                    else if (!deadPlayer.TSPlayer.Group.HasPermission("vault.bypass.death"))
                    {
                        Journal.BankAccountTransferOptions options = Journal.BankAccountTransferOptions.MoneyFromPvP | Journal.BankAccountTransferOptions.AnnounceToReceiver | Journal.BankAccountTransferOptions.AnnounceToSender;

                        // deadPlayer.ChangeMoney(-penaltyAmmount, MoneyEventFlags.Death, true);

                        SEconomyPlugin.WorldAccount.TransferTo(deadPlayer.Index, -penaltyAmmount, options);
                    }
                }
            }
            else if (e.MsgID == PacketTypes.PlayerDamage)
            {
                // Console.WriteLine("(SendData) PlayerDamage -> 1:{0} 2:{4} 3:{5} 4:{6} 5:{1} remote:{2} ignore:{3}", e.number, e.number5, e.remoteClient, e.ignoreClient, e.number2, e.number3, e.number4);
                // 1: pID, ignore: Who, 2: dir, 3:dmg, 4:pvp;
                if (e.number4 == 1)   // if PvP {
                {
                    var player = PlayerList[e.number];

                    if (player != null)
                    {
                        player.LastPVPID = e.ignoreClient;
                    }
                }
            }
        }
        /// <summary>
        /// Compresses all transactions into one line.  Doing this is going to remove all transaction history but you gain space and processing speed
        /// </summary>
        public static void SquashJournal()
        {
            int       bankAccountCount = BankAccounts.Count();
            int       tranCount        = Transactions.Count();
            XDocument newJournal       = NewJournal();

            bool responsibleForTurningBackupsBackOn = false;

            Console.WriteLine("seconomy xml: beginning Squash");

            if (SEconomyPlugin.BackupCanRun == true)
            {
                SEconomyPlugin.BackupCanRun        = false;
                responsibleForTurningBackupsBackOn = true;
            }

            for (int i = 0; i < bankAccountCount; i++)
            {
                XBankAccount account = BankAccounts.ElementAtOrDefault(i);
                if (account != null)
                {
                    //update account balance
                    account.SyncBalance();

                    string line = string.Format("\r [squash] {0:p} {1}", (double)i / (double)bankAccountCount, account.UserAccountName);
                    SEconomyPlugin.FillWithSpaces(ref line);

                    Console.Write(line);

                    //copy the bank account from the old journal into the new one
                    newJournal.Element("Journal").Element("BankAccounts").Add((XElement)account);

                    //Add the squished summary
                    XTransaction transSummary = new XTransaction(account.Balance);
                    transSummary.BankAccountTransactionK = RandomString(13);
                    transSummary.BankAccountFK           = account.BankAccountK;
                    transSummary.Flags              = BankAccountTransactionFlags.FundsAvailable | BankAccountTransactionFlags.Squashed;
                    transSummary.Message            = "Transaction squash";
                    transSummary.TransactionDateUtc = DateTime.UtcNow;

                    newJournal.Element("Journal").Element("Transactions").Add((XElement)transSummary);
                }
            }

            //abandon the old journal and assign the squashed one
            XmlJournal = newJournal;

            Console.WriteLine("re-syncing online accounts.");

            foreach (XBankAccount account in BankAccounts)
            {
                XBankAccount runtimeAccount = GetBankAccount(account.BankAccountK);
                if (runtimeAccount != null && runtimeAccount.Owner != null)
                {
                    Console.WriteLine("re-syncing {0}", runtimeAccount.Owner.TSPlayer.Name);
                    runtimeAccount.SyncBalance();
                }
            }

            SaveXml(Configuration.JournalPath);

            //the backups could already have been disabled by something else.  We don't want to be the ones turning it back on
            if (responsibleForTurningBackupsBackOn)
            {
                SEconomyPlugin.BackupCanRun = true;
            }
        }
Example #10
0
        void BuyItem(CommandArgs args)
        {
            if (args.Parameters.Count < 1 || args.Parameters.Count > 2)
            {
                args.Player.SendErrorMessage("Invalid syntax! Proper syntax: /buy <itemname> [stack]");
                return;
            }
            if (TShock.Regions.GetRegionByName("shop").Name != "" || TShock.Regions.GetRegionByName("shop") != null)
            {
                string currentregionlist = "";
                var    currentregion     = TShock.Regions.InAreaRegionName(args.Player.TileX, args.Player.TileY);
                if (currentregion.Count > 0)
                {
                    currentregionlist = string.Join(",", currentregion.ToArray());
                }

                if (!currentregionlist.Contains("shop"))
                {
                    args.Player.SendErrorMessage("You must be at /warp shop to purchase items.");
                    return;
                }
            }
            int stack = 1;

            long[]        coins  = new long[4];
            EconomyPlayer player = SEconomyPlugin.GetEconomyPlayerSafe(args.Player.Name);
            Money         money;

            money = player.BankAccount.Balance;
            if (args.Parameters.Count == 2)
            {
                try
                {
                    stack = Convert.ToInt32(args.Parameters[1]);
                }
                catch
                {
                    stack = 1;
                }
            }

            else
            {
                stack = 1;
            }


            var items = TShock.Utils.GetItemByIdOrName(args.Parameters[0]);

            if (items.Count > 1)
            {
                args.Player.SendErrorMessage(string.Format("More than one ({0}) item matched!", items.Count));
            }
            if (items.Count == 1)
            {
                if (args.Player.InventorySlotAvailable || items[0].name.Contains("Coin"))
                {
                    try
                    {
                        int  copper;
                        int  silver;
                        int  gold;
                        int  maxstack;
                        bool forsale;

                        if (SqlManager.GetInfo(items[0].name, out copper, out silver, out gold, out maxstack, out forsale))
                        {
                            if (stack > maxstack)
                            {
                                stack = maxstack;
                            }
                            int price;

                            price = ((gold * 10000) + (silver * 100) + copper) * stack;
                            if (SEconomyPlugin.Configuration.MoneyConfiguration.UseQuadrantNotation == true)
                            {
                                int copperb = Convert.ToInt32(player.BankAccount.Balance.Copper);
                                int silverb = Convert.ToInt32(player.BankAccount.Balance.Silver);
                                int goldb   = Convert.ToInt32(player.BankAccount.Balance.Gold);
                                int platb   = Convert.ToInt32(player.BankAccount.Balance.Platinum);
                                if (((platb * 1000000) + (goldb * 10000) + (silverb * 100) + copper) < price && price != 0)
                                {
                                    args.Player.SendErrorMessage("You do not have enough money to buy " + stack + " " + items[0].name + "(s).");
                                    return;
                                }
                                else
                                {
                                    if (price != 0)
                                    {
                                        player.BankAccount.TransferTo(SEconomyPlugin.WorldAccount, price, BankAccountTransferOptions.None);
                                    }
                                    args.Player.GiveItemCheck(items[0].type, items[0].name, items[0].width, items[0].height, stack);
                                    args.Player.SendSuccessMessage("Bought " + stack + " " + items[0].name + "(s) for " +
                                                                   gold + " " + SEconomyPlugin.Configuration.MoneyConfiguration.Quadrant1FullName +
                                                                   silver + " " + SEconomyPlugin.Configuration.MoneyConfiguration.Quadrant2FullName + " and " +
                                                                   copper + " " + SEconomyPlugin.Configuration.MoneyConfiguration.Quadrant3FullName + ".");
                                    Log.Info(args.Player.Name + " bought " + stack + " " + items[0].name + "(s) for " +
                                             gold + " " + SEconomyPlugin.Configuration.MoneyConfiguration.Quadrant1FullName +
                                             silver + " " + SEconomyPlugin.Configuration.MoneyConfiguration.Quadrant2FullName + " and " +
                                             copper + " " + SEconomyPlugin.Configuration.MoneyConfiguration.Quadrant3FullName + ".");
                                }
                            }
                            else
                            {
                                if (player.BankAccount.Balance.Value < price && price != 0)
                                {
                                    args.Player.SendErrorMessage("You do not have enough money to buy " + stack + " " + items[0].name + "(s).");
                                    return;
                                }
                                if (price != 0)
                                {
                                    player.BankAccount.TransferTo(SEconomyPlugin.WorldAccount, price, BankAccountTransferOptions.None);
                                }
                                args.Player.GiveItemCheck(items[0].type, items[0].name, items[0].width, items[0].height, stack);
                                args.Player.SendSuccessMessage("Bought " + stack + " " + items[0].name + "(s) for " +
                                                               price + " " + SEconomyPlugin.Configuration.MoneyConfiguration.MoneyNamePlural + ".");
                                Log.Info(args.Player.Name + " bought " + stack + " " + items[0].name + "(s) for " +
                                         price + " " + SEconomyPlugin.Configuration.MoneyConfiguration.MoneyNamePlural + ".");
                            }

                            if (forsale == false)
                            {
                                args.Player.SendErrorMessage("That item is not for sale.");
                                return;
                            }
                        }
                        else
                        {
                            args.Player.SendErrorMessage("Something went wrong. Please try again later.");
                        }
                    }
                    catch (Exception ex)
                    {
                        args.Player.SendErrorMessage("Failed to buy item(s).");
                        Log.Error("Failed to give item to " + args.Player.Name + ". (ShopSystem)");
                        Log.Error(ex.ToString());
                    }
                }
                else
                {
                    args.Player.SendErrorMessage("You don't have any free slots!");
                }
            }
            else
            {
                args.Player.SendErrorMessage("Invalid item type!");
            }
        }