AddSetting() публичный Метод

Adds or replaces a setting to the table to be saved with a null value.
public AddSetting ( String sectionName, String settingName ) : void
sectionName String Section to add under.
settingName String Key name to add.
Результат void
Пример #1
0
        private void frmMain_Load(object sender, EventArgs e)
        {

            dataGridView1.DataSource = null;
            DataSet ds = YAMS.Database.ReturnLogRows();
            dataGridView1.DataSource = ds.Tables[0];

            this.checkBox1.Checked = YAMS.Util.HasJRE();
            this.checkBox2.Checked = YAMS.Util.HasJDK();

            this.textBox1.Text = YAMS.Util.JavaPath();
            this.textBox2.Text = YAMS.Util.JavaPath("jdk");

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName;
            watcher.Filter = "*.sdf";
            //watcher.NotifyFilter = NotifyFilters.LastWrite;

            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;

            IniParser parser = new IniParser(@"server.properties");
            txtIniCheck.Text = parser.GetSetting("ROOT", "level-name");

            parser.AddSetting("ROOT", "level-name", "world");
            parser.SaveSettings();

        }
Пример #2
0
        public MCServer(int intServerID)
        {
            this.ServerID = intServerID;

            //Set this first so that we can use it right away
            this.ServerDirectory = Core.StoragePath + this.ServerID.ToString() + @"\";

            //If server is a pre-0.2.3 then we need to move everything back to default layout to support a lot of bukkit plugins
            if (Directory.Exists(Core.StoragePath + this.ServerID.ToString() + "\\config\\")) {
                //This is our old config and working dir, so we need everything out of it moved into the main dir
                try {
                    Util.Copy(Core.StoragePath + this.ServerID.ToString() + "\\config\\", this.ServerDirectory);
                    Directory.Delete(Core.StoragePath + this.ServerID.ToString() + "\\config\\", true);
                    //We also need to amend the properties file to include the new world path
                    IniParser parser = new IniParser(this.ServerDirectory + @"\server.properties");
                    parser.AddSetting("ROOT", "level-name", "world");
                    parser.SaveSettings("#Minecraft server properties\r\n#Generated by YAMS " + DateTime.Now.ToString() + "\r\n");
                }
                catch(Exception e) {
                    Database.AddLog("Unable to move config directory, this will have to be done manually to avoid losing settings: " + e.Message, "app", "error");
                }
            }

            //Set this here to catch any old references to it.
            this.strWorkingDir = this.ServerDirectory;

            this.bolEnableJavaOptimisations = Convert.ToBoolean(Database.GetSetting(this.ServerID, "ServerEnableOptimisations"));
            this.intAssignedMem = Convert.ToInt32(Database.GetSetting(this.ServerID, "ServerAssignedMemory"));
            this.ServerTitle = Convert.ToString(Database.GetSetting(this.ServerID, "ServerTitle"));
            this.ServerType = Convert.ToString(Database.GetSetting(this.ServerID, "ServerType"));
            this.LogonMode = Convert.ToString(Database.GetSetting(this.ServerID, "ServerLogonMode"));
            this.Port = Convert.ToInt32(this.GetProperty("server-port"));
        }
Пример #3
0
        public string backupStats()
        {
            string str = "backup_" + (object)DateTime.Now.Hour + "h-" + (object)DateTime.Now.Minute + "m_" + (object)DateTime.Now.Day + "-" + (object)DateTime.Now.Month + "-" + (object)DateTime.Now.Year + ".ini";

            File.Create(this.get_ModuleFolder() + "\\" + str).Close();
            IniParser iniParser = new IniParser(this.get_ModuleFolder() + "\\" + str);

            foreach (object key in this.ds.Keys("Rank++Time"))
            {
                iniParser.AddSetting("Kills", key.ToString(), this.ds.Get("Rank++Kills", key).ToString());
                iniParser.AddSetting("Deaths", key.ToString(), this.ds.Get("Rank++Deaths", key).ToString());
                iniParser.AddSetting("Headshots", key.ToString(), this.ds.Get("Rank++Headshots", key).ToString());
                iniParser.AddSetting("Time", key.ToString(), this.ds.Get("Rank++Time", key).ToString());
                iniParser.AddSetting("PVE", key.ToString(), this.ds.Get("Rank++PVE", key).ToString());
                iniParser.AddSetting("Gathering", key.ToString(), this.ds.Get("Rank++Gathering", key).ToString());
            }
            iniParser.Save();
            return(str);
        }
Пример #4
0
 private void ReadConfig()
 {
     if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
     {
         File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
         ini = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
         ini.AddSetting("Config", "MessageBuy", MessageBuy);
         ini.AddSetting("Config", "MessageBuyChat1", MessageBuyChat1);
         ini.AddSetting("Config", "MessageBuyChat2", MessageBuyChat2);
         ini.AddSetting("Config", "MessageThanks", MessageThanks);
         ini.AddSetting("Config", "InventoryFull", InventoryFull);
         ini.AddSetting("Config", "MessageAlready", MessageAlready);
         ini.AddSetting("Config", "MessageAlready1", MessageAlready1);
         ini.Save();
     }
     else
     {
         ini             = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
         MessageBuy      = ini.GetSetting("Config", "MessageBuy");
         MessageBuyChat1 = ini.GetSetting("Config", "MessageBuyChat1");
         MessageBuyChat2 = ini.GetSetting("Config", "MessageBuyChat2");
         MessageThanks   = ini.GetSetting("Config", "MessageThanks");
         InventoryFull   = ini.GetSetting("Config", "InventoryFull");
         MessageAlready  = ini.GetSetting("Config", "MessageAlready");
         MessageAlready1 = ini.GetSetting("Config", "MessageAlready1");
     }
     if (!File.Exists(Path.Combine(ModuleFolder, "users.ini")))
     {
         File.Create(Path.Combine(ModuleFolder, "users.ini")).Dispose();
         users = new IniParser(Path.Combine(ModuleFolder, "users.ini"));
     }
     else
     {
         users = new IniParser(Path.Combine(ModuleFolder, "users.ini"));
     }
 }
Пример #5
0
        public override void Initialize()
        {
            rnd  = new System.Random();
            cfg  = new IniParser(Path.Combine(ModuleFolder, "Messages.ini"));
            cfg1 = new IniParser(Path.Combine(ModuleFolder, "Notices.ini"));

            if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                Settings.AddSetting("Messages", "EnabledMessages", "true");
                Settings.AddSetting("Messages", "BroadCastTime", BroadCastTime.ToString());
                Settings.AddSetting("Messages", "Registered", RegisterMessages.ToString());
                Settings.AddSetting("Notices", "EnableNotices", "true");
                Settings.AddSetting("Notices", "NoticeTime", NoticeTime.ToString());
                Settings.AddSetting("Notices", "Registered", RegisterNotice.ToString());
                Settings.Save();
            }
            else
            {
                Settings         = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                EnableMessages   = bool.Parse(Settings.GetSetting("Messages", "EnabledMessages"));
                BroadCastTime    = int.Parse(Settings.GetSetting("Messages", "BroadCastTime"));
                RegisterMessages = int.Parse(Settings.GetSetting("Messages", "Registered"));
                EnableNotice     = bool.Parse(Settings.GetSetting("Notices", "EnableNotices"));
                NoticeTime       = int.Parse(Settings.GetSetting("Notices", "NoticeTime"));
                RegisterNotice   = int.Parse(Settings.GetSetting("Notices", "Registered"));
            }
            if (EnableMessages)
            {
                Logger.Log("ChatBroadcast enabled");
                BroadCast(BroadCastTime * 1000, null).Start();
            }
            if (EnableNotice)
            {
                Logger.Log("Notices enabled");
                Notice(NoticeTime * 1000, null).Start();
            }
        }
Пример #6
0
        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            if (txtUsername.Text == string.Empty)
            {
                MostrarDialogo("Error", "Please enter an Username");
                return;
            }
            else if (txtApiKey.Text == string.Empty)
            {
                MostrarDialogo("Error", "Please enter an API Key");
                return;
            }
            else if (txtApiKey.Text.Length < 64)
            {
                MostrarDialogo("Error", "Please enter a valid API Key");
                txtApiKey.Text = string.Empty;
                return;
            }
            string  url     = string.Format("https://dadice.com/api/balance?username={0}&key={1}", txtUsername.Text, txtApiKey.Text);
            Balance balance = _download_serialized_json_data <Balance>(url);

            if (balance.status)
            {
                if (chkLogin.IsChecked != null && (bool)chkLogin.IsChecked)
                {
                    _parser.AddSetting("DADICE", "USERNAME", txtUsername.Text);
                    _parser.AddSetting("DADICE", "APIKEY", txtApiKey.Text);
                    _parser.SaveSettings();
                }
                DaDiceMain main = new DaDiceMain(new LoginData(txtUsername.Text, txtApiKey.Text), balance.balance);
                main.Show();
                Close();
            }
            else
            {
                MostrarDialogo("Error", balance.error);
            }
        }
Пример #7
0
        public void On_PluginInit()
        {
            Author  = "Pluton Team";
            Version = "0.1.4 (beta)";
            About   = "All non-core Pluton commands and functions all rolled into a plugin.";

            //Create Config if doesnt exist else load it
            if (Plugin.IniExists("PlutonEssentials"))
            {
                Debug.Log("PlutonEssentials config loaded!");
            }
            else
            {
                IniParser ConfigFile = Plugin.CreateIni("PlutonEssentials");
                Debug.Log("PlutonEssentials config created!");
                Debug.Log("The config will be filled with the default values.");
                ConfigFile.AddSetting("Config", "craftTimescale", "1.0");
                ConfigFile.AddSetting("Config", "resourceGatherMultiplier", "1.0");

                ConfigFile.AddSetting("Config", "permanentTime", "-1.0");
                ConfigFile.AddSetting("Config", "timescale", "30.0");

                ConfigFile.AddSetting("Config", "broadcastInterval", "600000");
                ConfigFile.AddSetting("Config", "Broadcast", "true");
                ConfigFile.AddSetting("Config", "Help", "true");
                ConfigFile.AddSetting("Config", "Welcome", "true");

                ConfigFile.AddSetting("Config", "StructureRecorder", "false");

                ConfigFile.AddSetting("Config", "Server_Image", "");
                ConfigFile.AddSetting("Config", "Server_Description", "This server is running Pluton Framework and is awesome!");
                ConfigFile.AddSetting("Config", "Server_Url", "");

                ConfigFile.AddSetting("Config", "NoChatSpam", "true");
                ConfigFile.AddSetting("Config", "NoVacBans", "false");
                ConfigFile.AddSetting("Config", "PvE", "true");

                ConfigFile.AddSetting("Commands", "ShowMyStats", "mystats");
                ConfigFile.AddSetting("Commands", "ShowStatsOther", "statsof");

                ConfigFile.AddSetting("Commands", "ShowLocation", "whereami");
                ConfigFile.AddSetting("Commands", "ShowOnlinePlayers", "players");

                ConfigFile.AddSetting("Commands", "Help", "help");
                ConfigFile.AddSetting("Commands", "Commands", "commands");

                ConfigFile.AddSetting("Commands", "Description", "whatis");
                ConfigFile.AddSetting("Commands", "Usage", "howto");
                ConfigFile.AddSetting("Commands", "About", "about");

                ConfigFile.AddSetting("Commands", "StartStructureRecording", "srstart");
                ConfigFile.AddSetting("Commands", "StopStructureRecording", "srstop");
                ConfigFile.AddSetting("Commands", "BuildStructure", "srbuild");

                ConfigFile.AddSetting("HelpMessage", "1", "");

                ConfigFile.AddSetting("BroadcastMessage", "1", "This server is powered by Pluton, the new servermod!");
                ConfigFile.AddSetting("BroadcastMessage", "2", "For more information visit our github repo: github.com/Notulp/Pluton or our forum: pluton-team.org");

                ConfigFile.AddSetting("WelcomeMessage", "1", "This server is powered by Pluton!");
                ConfigFile.AddSetting("WelcomeMessage", "2", "Visit pluton-team.org for more information or to report bugs!");

                ConfigFile.AddSetting("NoChatSpam", "NoChatSpamCooldown", "2000");
                ConfigFile.AddSetting("NoChatSpam", "NoChatSpamMaxMessages", "4");
                ConfigFile.AddSetting("NoChatSpam", "NoChatSpamIgnoreMod", "false");

                ConfigFile.AddSetting("NoVacBans", "MaxAllowed", "2");

                ConfigFile.Save();
            }

            IniParser GetConfig = Plugin.GetIni("PlutonEssentials");

            //Set Callbacks for commands
            Commands.Register(GetConfig.GetSetting("Commands", "ShowMyStats")).setCallback(Mystats);
            Commands.Register(GetConfig.GetSetting("Commands", "ShowStatsOther")).setCallback(Statsof);
            Commands.Register(GetConfig.GetSetting("Commands", "ShowLocation")).setCallback(Whereami);
            Commands.Register(GetConfig.GetSetting("Commands", "ShowOnlinePlayers")).setCallback(Players);
            Commands.Register(GetConfig.GetSetting("Commands", "Help")).setCallback(Help);
            Commands.Register(GetConfig.GetSetting("Commands", "Commands")).setCallback(CommandS);
            Commands.Register(GetConfig.GetSetting("Commands", "Description")).setCallback(Whatis);
            Commands.Register(GetConfig.GetSetting("Commands", "Usage")).setCallback(Howto);
            Commands.Register(GetConfig.GetSetting("Commands", "About")).setCallback(AboutCMD);

            //Structure Recorder
            StructureRecorder = bool.Parse(GetConfig["Config"]["StructureRecorder"]) == false;
            if (StructureRecorder)
            {
                Commands.Register(GetConfig.GetSetting("Commands", "StartStructureRecording")).setCallback(Srstart);
                Commands.Register(GetConfig.GetSetting("Commands", "StopStructureRecording")).setCallback(Srstop);
                Commands.Register(GetConfig.GetSetting("Commands", "BuildStructure")).setCallback(Srbuild);
            }

            DataStore.Flush("StructureRecorder");
            DataStore.Flush("StructureRecorderEveryone");

            if (Server.Loaded)
            {
                Structures = new Dictionary <string, Structure>();
                LoadStructures();
            }

            //Broadcast settings
            if (GetConfig.GetBoolSetting("Config", "Broadcast"))
            {
                int broadcast_time = int.Parse(GetConfig.GetSetting("Config", "broadcastInterval", "600000"));
                Plugin.CreateTimer("Advertise", broadcast_time);
                foreach (string key in GetConfig.EnumSection("BroadcastMessage"))
                {
                    if (key == null)
                    {
                        return;
                    }
                    BroadcastMessage.Add(GetConfig.GetSetting("BroadcastMessage", key));
                }
            }

            //Help Message
            if (GetConfig.GetBoolSetting("Config", "Help", true))
            {
                foreach (string key in GetConfig.EnumSection("HelpMessage"))
                {
                    if (key == null)
                    {
                        return;
                    }
                    HelpMessage.Add(GetConfig.GetSetting("HelpMessage", key));
                }
            }

            //Welcome Message
            Welcome = GetConfig.GetBoolSetting("Config", "Welcome", true);
            if (Welcome)
            {
                foreach (string key in GetConfig.EnumSection("WelcomeMessage"))
                {
                    if (key == null)
                    {
                        return;
                    }
                    WelcomeMessage.Add(GetConfig.GetSetting("WelcomeMessage", key));
                }
            }

            //NoChatSpam Global variable
            NoChatSpam            = GetConfig.GetBoolSetting("Config", "NoChatSpam", true);
            NoChatSpamCooldown    = int.Parse(GetConfig.GetSetting("NoChatSpam", "NoChatSpamCooldown", "2000"));
            NoChatSpamMaxMessages = int.Parse(GetConfig.GetSetting("NoChatSpam", "NoChatSpamMaxMessages", "4"));
            NoChatSpamIgnoreMod   = GetConfig.GetBoolSetting("NoChatSpam", "NoChatSpamIgnoreMod");

            //Set New Server Settings
            ConVar.Server.pve         = GetConfig.GetBoolSetting("Config", "PvE", true);
            ConVar.Server.description = GetConfig.GetSetting("Config", "Server_Description");
            ConVar.Server.headerimage = GetConfig.GetSetting("Config", "Server_Image");
            ConVar.Server.url         = GetConfig.GetSetting("Config", "Server_Url");

            //Check for updates
            var getjson = JSON.Object.Parse(Web.GET(latest)).GetString("plutonVersion");
            var getver  = Pluton.Bootstrap.Version;

            if (getjson != getver)
            {
                UpdateAvailable = true;
            }

            //NoVacBans
            NoVacBans  = GetConfig.GetBoolSetting("Config", "NoVacBans", false);
            MaxVacBans = int.Parse(GetConfig.GetSetting("NoVacBans", "MaxVacBans", "2"));
        }
Пример #8
0
        private void savePrefs()
        {
            IniParser parser = new IniParser(@"CP1252Fixer.ini");

            for (int i = 0; i < CMOptions.Length; ++i)
            {
                parser.AddSetting("options", CMOptions[i].text, (CMOptions[i].active ? "true" : "false"));
            }
            parser.SaveSettings();
        }
Пример #9
0
        private bool ReloadConfig()
        {
            if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                Settings.AddSetting("Settings", "UseDayLimit", "True");
                Settings.AddSetting("Settings", "MaxDays", "14");
                Settings.AddSetting("Settings", "UseDecay", "False");
                Settings.AddSetting("Settings", "DecayTimer", "30");
                Settings.AddSetting("Settings", "WipeCheckTimer", "30");
                Settings.AddSetting("Settings", "Broadcast", "True");
                Settings.AddSetting("Settings", "UserDataPath", "\\rust_server_Data\\userdata\\");
                Settings.Save();
            }
            if (!File.Exists(Path.Combine(ModuleFolder, "WhiteList.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "WhiteList.ini")).Dispose();
                WhiteList = new IniParser(Path.Combine(ModuleFolder, "WhiteList.ini"));
                WhiteList.AddSetting("WhiteList", "1234212312312", "1");
                WhiteList.Save();
            }
            if (!File.Exists(Path.Combine(ModuleFolder, "Players.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Players.ini")).Dispose();
                CollectedIDs.Clear();
                foreach (var x in Server.GetServer().Players)
                {
                    CollectedIDs[x.UID] = DateTime.Today;
                }
            }


            Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
            try
            {
                MaxDays        = int.Parse(Settings.GetSetting("Settings", "MaxDays"));
                DecayTimer     = int.Parse(Settings.GetSetting("Settings", "DecayTimer"));
                WipeCheckTimer = int.Parse(Settings.GetSetting("Settings", "WipeCheckTimer"));
                UseDayLimit    = Settings.GetBoolSetting("Settings", "UseDayLimit");
                UseDecay       = Settings.GetBoolSetting("Settings", "UseDecay");
                Broadcast      = Settings.GetBoolSetting("Settings", "Broadcast");
                UserDataPath   = @Settings.GetSetting("Settings", "UserDataPath");
            }
            catch (Exception ex)
            {
                Fougerite.Logger.LogError("[Wiper] Failed to read config, possible wrong value somewhere! Ex: " + ex);
                return(false);
            }
            LoadDecayList();


            WhiteList = new IniParser(Path.Combine(ModuleFolder, "WhiteList.ini"));
            string[] enumm = WhiteList.EnumSection("WhiteList");
            if (enumm.Length > 0)
            {
                foreach (var x in enumm)
                {
                    try
                    {
                        ulong id = ulong.Parse(x);
                        WList.Add(id);
                    }
                    catch
                    {
                        Logger.LogError("[Wiper] Failed to parse whitelist for " + x);
                        return(false);
                    }
                }
            }
            return(true);
        }
Пример #10
0
        public bool ToIni(string inifilename = "DataStore")
        {
            string inipath = Path.Combine(Config.GetPublicFolder(), inifilename.RemoveChars(new char[] { '.', '/', '\\', '%', '$' }).RemoveWhiteSpaces() + ".ini");
            File.WriteAllText(inipath, "");
            IniParser ini = new IniParser(inipath);
            ini.Save();

            foreach (string section in this.datastore.Keys) {
                Hashtable ht = (Hashtable)this.datastore[section];
                foreach (object setting in ht.Keys) {
                    try {
                        string key = "NullReference";
                        string val = "NullReference";
                        if (setting != null) {
                            if (setting.GetType().GetMethod("ToString", Type.EmptyTypes) == null) {
                                key = "type:" + setting.GetType().ToString();
                            } else {
                                key = setting.ToString();
                            }
                        }

                        if (ht[setting] != null) {
                            if (ht[setting].GetType().GetMethod("ToString", Type.EmptyTypes) == null) {
                                val = "type:" + ht[setting].GetType().ToString();
                            } else {
                                val = ht[setting].ToString();
                            }            
                        }

                        ini.AddSetting(section, key, val);
                    } catch (Exception ex) {
                        Logger.LogException(ex);
                    }
                }
            }
            ini.Save();
            return true;           
        }
Пример #11
0
 public void SaveProperty(string strPropertyName, string strPropertyValue)
 {
     //If there is already a partially updated file, we want to put this value in the new file
     string strPathToRead;
     if (File.Exists(this.ServerDirectory + @"\server.properties.UPDATE")) strPathToRead = this.ServerDirectory + @"\server.properties.UPDATE";
     else strPathToRead = this.ServerDirectory + @"\server.properties";
     IniParser parser = new IniParser(strPathToRead);
     parser.AddSetting("ROOT", strPropertyName, strPropertyValue);
     parser.SaveSettings(this.ServerDirectory + @"\server.properties.UPDATE", "#Minecraft server properties\r\n#Generated by YAMS " + DateTime.Now.ToString() + "\r\n");
 }
Пример #12
0
        private void btSave_Click(object sender, EventArgs e)
        {
            if (!File.Exists(textBoxGame.Text))
            {
                DialogResult = DialogResult.None;
                textBoxGame.Focus();
                MessageBox.Show("Invalid witcher3.exe path", "failed to save.");
                return;
            }

            if (!File.Exists(textBoxWcc.Text))
            {
                DialogResult = DialogResult.None;
                textBoxWcc.Focus();
                MessageBox.Show("Invalid wcc_lite.exe path", "failed to save.");
                return;
            }

            MainController.Get().ProjectStatus  = EProjectStatus.Busy;
            MainController.Get().StatusProgress = 0;

            // get configs
            var config   = MainController.Get().Configuration;
            var uiconfig = UIController.Get().Configuration;

            // Apply Theme
            bool applyTheme = uiconfig.ColorTheme != (EColorThemes)comboBoxTheme.SelectedItem;

            // save settings
            config.ExecutablePath = textBoxGame.Text;
            config.WccLite        = textBoxWcc.Text;

            // double check that r4depot exists
            if (string.IsNullOrEmpty(config.DepotPath))
            {
                DirectoryInfo wccDir     = new FileInfo(textBoxWcc.Text).Directory.Parent.Parent;
                string        wcc_r4data = Path.Combine(wccDir.FullName, "r4data");
                if (Directory.Exists(wcc_r4data))
                {
                    config.DepotPath = wcc_r4data;
                }
            }
            config.DepotPath  = textBoxDepot.Text;
            config.GameModDir = textBoxModDir.Text;
            config.GameDlcDir = textBoxDlcDir.Text;

            config.TextLanguage              = txTextLanguage.Text;
            config.VoiceLanguage             = txVoiceLanguage.Text;
            config.UncookExtension           = (EUncookExtension)comboBoxExtension.SelectedItem;
            config.IsWelcomeFormDisabled     = checkBoxDisableWelcomeForm.Checked;
            config.IsAutoInstallModsDisabled = !checkBoxAutoInstall.Checked;

            uiconfig.ColorTheme  = (EColorThemes)comboBoxTheme.SelectedItem;
            config.UpdateChannel = (EUpdateChannel)comboBoxUpdateChannel.SelectedItem;

            // save configs
            config.Save();
            uiconfig.Save();

            MainController.Get().UpdateWccHelper(config.WccLite);


            if (applyTheme)
            {
                MockKernel.Get().Window.GlobalApplyTheme();
                RequestApplyTheme?.Invoke();
            }

            /// debug console enabling
            try
            {
                IniParser ip = new IniParser(Path.Combine(MainController.Get().Configuration.GameRootDir, "bin\\config\\base\\general.ini"));
                if (!ip.HasSection("General") || ip.GetSetting("General", "DBGConsoleOn", true) != "true")
                {
                    if (MessageBox.Show(
                            "WolvenKit has detected that your game has the debug console disabled. It is a useful tool when testing mods. Would you like it to be enabled?",
                            "Debug console enabling", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ip.AddSetting("General", "DBGConsoleOn", "true");
                        ip.Save();
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

            // patch wcc_lite
            try
            {
                using (var fs = new FileStream(textBoxWcc.Text, FileMode.Open))
                    using (var bw = new BinaryWriter(fs))
                    {
                        var shawcc = System.Security.Cryptography.SHA256.Create().ComputeHash(fs).Aggregate("", (c, n) => c += n.ToString("x2"));
                        switch (shawcc)
                        {
                        case wcc_sha256:
                        {
                            if (MessageBox.Show("wcc_lite is a great tool by CD Projekt red but" +
                                                "due to some internal problems they didn't really have time to properly develop it, and is very slow " +
                                                "because it is searching for a CD Projekt red mssql server.\n" +
                                                "WolvenKit can patch this with a method figured out by blobbins on the witcher 3 forums." +
                                                "Would you like to perform this patch?", "wcc_lite faster patch", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                                DialogResult.Yes)
                            {
                                //We perform the patch
                                bw.BaseStream.Seek(0x00713CD0, SeekOrigin.Begin);
                                bw.Write(new byte[0xDD].Select(x => x = 0x90).ToArray());

                                //Recompute hash
                                fs.Seek(0, SeekOrigin.Begin);
                                shawcc = System.Security.Cryptography.SHA256.Create().ComputeHash(fs).Aggregate("", (c, n) => c += n.ToString("x2"));
                                if (shawcc == wcc_sha256_patched)
                                {
                                    MessageBox.Show("Succesfully patched!", "Patch completed", MessageBoxButtons.OK,
                                                    MessageBoxIcon.Information);
                                }
                                else
                                {
                                    MessageBox.Show("Failed to patch! Please reinstall wcc_lite and try again",
                                                    "Patch completed", MessageBoxButtons.OK,
                                                    MessageBoxIcon.Error);
                                }
                            }



                            break;
                        }

                        case wcc_sha256_patched2:
                        case wcc_sha256_patched:
                        {
                            //Do nothing we are cool.
                            break;
                        }

                        default:
                        {
                            DialogResult = DialogResult.None;
                            textBoxGame.Focus();
                            MessageBox.Show("Invalid wcc_lite.exe path you seem to have on older version",
                                            "failed to save.");
                            return;
                        }
                        }
                    }
            }
            catch (UnauthorizedAccessException)
            {
                //wcc_lite is installed to C:\\Program files
                MessageBox.Show("Please restart WolvenKit as administrator. Couldn't access " + textBoxWcc.Text,
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // Exit with error code 0 so we don't raise a windows error and the user can restart it so we have access to the files.
                Environment.Exit(0);
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

            MainController.Get().StatusProgress = 100;
            MainController.Get().ProjectStatus  = EProjectStatus.Ready;
        }
Пример #13
0
        private void OnEntityDeployed(Fougerite.Player oldplayer, Entity entity, Fougerite.Player player)
        {
            var internalerror = false;

            if (CanBypass(player))
            {
                return;
            }

            var thread = new Thread(() =>
            {
                try
                {
                    if (entity.Name.Contains("Pillar"))
                    {
                        var height = entity.Name.Contains("WoodPillar")
                            ? _settings["Maximum Wood Height"]
                            : _settings["Maximum Metal Height"];

                        foreach (var ent in entity.GetLinkedStructs())
                        {
                            if (!ent.Name.Contains("Foundation"))
                            {
                                continue;
                            }

                            if (((entity.Y - ent.Y) / 4) > height)
                            {
                                if (_refund)
                                {
                                    player.Inventory.AddItem(entity.Name, 1);
                                    player.InventoryNotice("1 x " + entity.Name);
                                }

                                if (!entity.IsDestroyed)
                                {
                                    entity.Destroy();
                                }

                                player.Notice("You have reached the maximum build height!");
                            }

                            break;
                        }
                    }
                    else if (entity.Name.Contains("Foundation"))
                    {
                        var foundations = entity.Name.Contains("WoodFoundation")
                            ? _settings["Maximum Wood Foundations"]
                            : _settings["Maximum Metal Foundations"];

                        var count = 0f;

                        foreach (var ent in entity.GetLinkedStructs())
                        {
                            if (!ent.Name.Contains("Foundation"))
                            {
                                continue;
                            }
                            count += 1f;
                        }

                        if (count >= foundations)
                        {
                            if (_refund)
                            {
                                player.Inventory.AddItem(entity.Name);
                                player.InventoryNotice("1 x " + entity.Name);
                            }

                            if (!entity.IsDestroyed)
                            {
                                entity.Destroy();
                            }

                            player.Notice("You have reached the maximum foundations!");
                        }
                    }
                }
                catch (Exception e)
                {
                    internalerror = true;
                    if (!File.Exists(Path.Combine(ModuleFolder, "ErrorLog.ini")))
                    {
                        File.Create(Path.Combine(ModuleFolder, "ErrorLog.ini")).Dispose();
                        _errorLog = new IniParser(Path.Combine(ModuleFolder, "ErrorLog.ini"));
                        _errorLog.Save();
                    }
                    _errorLog = new IniParser(Path.Combine(ModuleFolder, "ErrorLog.ini"));

                    _errorLog.AddSetting(DateTime.Now.ToString("dd_MM_yyyy"), DateTime.Now.ToString("h:mm:ss"), Author + ":" + Version + " | Message: " + e.Message + " StackTrace: " + e.StackTrace);
                    _errorLog.Save();
                }
            })
            {
                IsBackground = true
            };

            thread.Start();

            if (internalerror)
            {
                if (player.Admin || player.Moderator)
                {
                    player.MessageFrom("BuildingRestriction", "Error in plugin, Check ErrorLog.ini for details on this error");
                }
                Logger.LogError("[BuildingRestriction] Error in plugin, See ErrorLog.ini for details!");
            }
        }
 private void SaveResetPwdINI()
 {
     parser.AddSetting("Password Settings", "DEFAULTPWD", DefaultPwd);
     parser.SaveSettings(ResetPwdINIPath.ToString());
 }
Пример #15
0
 public void Command(Player sender, string cmd, string[] args)
 {
     if (cmd == "jail")
     {
         if (sender.Admin || sender.Moderator && AllowMods)
         {
             sender.MessageFrom(Name, green + "Jail Remastered by " + cadet1 + Author);
             sender.MessageFrom(Name, cornflower + "/jail_send player time reason - sends a player to jail");
             sender.MessageFrom(Name, cornflower + "/jail_set radius - sends a jail");
             sender.MessageFrom(Name, cornflower + "/jail_del - deletes the jail");
             sender.MessageFrom(Name, cornflower + "/jail_free player - free someone");
         }
     }
     else if (cmd == "jail_send")
     {
         if (sender.Admin || sender.Moderator && AllowMods)
         {
             if (args.Length != 3)
             {
                 sender.Notice("☢", "Usage /jail_send player time reason", 20f);
                 return;
             }
             Player inmate = server.FindPlayer(args[0]);
             if (inmate == null)
             {
                 sender.Notice("☢", "Couldn't find the target user", 10f); return;
             }
             if (!inmate.IsAlive)
             {
                 sender.Notice("☢", inmate.Name + " seems to be dead wait for him to respawn", 10f); return;
             }
             if (list.ContainsSetting("inmates", inmate.SteamID))
             {
                 sender.Notice("☢", inmate.Name + " is already in jail", 10f); return;
             }
             if (!ini.ContainsSetting("jailloc", "location"))
             {
                 sender.Notice("☢", "You must have a jail", 10f); return;
             }
             if (!radius.ContainsKey("radius"))
             {
                 sender.Notice("☢", "Failed to find jail radius please reset the jail", 10f); return;
             }
             if (inmate.Admin && AdminProtection)
             {
                 sender.Notice("☢", "You cannot send admins to jail", 10f); return;
             }
             int     time    = Convert.ToInt32(args[1]);
             Vector3 loc     = util.ConvertStringToVector3(ini.GetSetting("jailloc", "location"));
             string  message = GlobalSendMessage.Replace("{inmate}", inmate.Name).Replace("{sender}", sender.Name).Replace("{time}", args[1]).Replace("{reason}", args[2]);
             list.AddSetting("inmates", inmate.SteamID, inmate.Name);
             list.AddSetting("jailreasons", inmate.SteamID, args[2]);
             list.AddSetting("previouslocations", inmate.SteamID, inmate.Location.ToString());
             list.Save();
             ds.Add("inmates", inmate.SteamID, "injail");
             ds.Save();
             inmate.MessageFrom(Name, ArrestMessage);
             server.BroadcastFrom(Name, message);
             inmate.TeleportTo(loc);
             inmate.AdjustCalorieLevel(100f);
             var dict = new Dictionary <string, object>();
             dict["inmate"] = inmate;
             Jailtimer(time * 60000, dict).Start();
             BlockCommands(inmate);
             Logger.Log("[Jail] " + inmate.Name + " was sended to jail by " + sender.Name + " for " + time + " minutes, for " + args[2]);
         }
         else
         {
             sender.Notice("✘", "You dont have permissions to use this command", 10f);
         }
     }
     else if (cmd == "jail_set")
     {
         if (sender.Admin || sender.Moderator && AllowMods)
         {
             if (args.Length != 1)
             {
                 sender.Notice("☢", "Usage /jail_set Radius");
                 return;
             }
             if (ini.ContainsSetting("jailloc", "location"))
             {
                 sender.Notice("☢", "Please remove your jail before setting new one");
                 return;
             }
             int     rad = Convert.ToInt32(args[0]);
             Vector3 loc = sender.Location;
             SetJail(loc, rad);
             sender.MessageFrom(Name, "Jail saved at " + sender.Location + " with a radius of " + rad);
         }
     }
     else if (cmd == "jail_del")
     {
         if (sender.Admin || sender.Moderator && AllowMods)
         {
             if (!ini.ContainsSetting("jailloc", "location"))
             {
                 sender.Notice("☢", "Failed to find jail", 10f);
                 return;
             }
             ini.DeleteSetting("jailloc", "location");
             ini.DeleteSetting("JailRadius", "radius");
             radius.Remove("radius");
             ini.Save();
             sender.Notice("☢", "The jail has been succesfully removed", 10f);
         }
     }
     else if (cmd == "jail_free")
     {
         if (sender.Admin || sender.Moderator && AllowMods)
         {
             if (args.Length != 1)
             {
                 sender.Notice("☢", "Usage /jail_free player", 10f);
                 return;
             }
             Player inmate = server.FindPlayer(args[0]);
             if (inmate == null)
             {
                 sender.Notice("☢", "Couldn't find the target user", 10f); return;
             }
             if (!ds.ContainsKey("inmates", inmate.SteamID))
             {
                 sender.Notice("☢", inmate.Name + " isnt in jail", 10f); return;
             }
             list.DeleteSetting("inmates", inmate.SteamID);
             list.DeleteSetting("jailreasons", inmate.SteamID);
             Vector3 loc = util.ConvertStringToVector3(list.GetSetting("previouslocations", inmate.SteamID));
             inmate.TeleportTo(loc);
             list.DeleteSetting("previouslocations", inmate.SteamID);
             string message = FreeMessage.Replace("inmate", inmate.Name);
             server.BroadcastFrom(Name, message);
             ini.Save();
             ds.Remove("inmates", inmate.SteamID);
             ds.Save();
         }
     }
 }
Пример #16
0
        public void Items()
        {
            string path = Path.Combine(GetPublicFolder(), "Items.ini");

            if (!File.Exists(path))
                File.AppendAllText(path, "");

            IniParser ini = new IniParser(path);

            foreach (ItemDefinition item in ItemManager.itemList) {
                ini.AddSetting(item.displayName.english, "itemid", item.itemid.ToString());
                ini.AddSetting(item.displayName.english, "category", item.category.ToString());
                ini.AddSetting(item.displayName.english, "shortname", item.shortname);
                ini.AddSetting(item.displayName.english, "description", item.displayDescription.english);
            }

            ini.Save();
        }
Пример #17
0
        private void ServerExited(object sender, EventArgs e)
        {
            DateTime datTimeStamp = DateTime.Now;
            Database.AddLog(datTimeStamp, "Server Exited", "server", "warn", false, this.ServerID);
            this.Running = false;
            Util.RemovePID(this.PID);
            //Close firewall
            if (Database.GetSetting("EnableOpenFirewall", "YAMS") == "true") Networking.CloseFirewallPort(this.Port);
            if (Database.GetSetting("EnablePortForwarding", "YAMS") == "true") Networking.CloseUPnP(this.Port);

            //Server has stopped, so clear out any entries in the user list
            this.Players.Clear();

            //Did the server stop safely?
            if (!this.SafeStop)
            {
                System.Threading.Thread.Sleep(10000);

                if (this.AgreeEULA)
                {
                    //It's the EULA message, let's clear it.
                    string strPathToRead = this.ServerDirectory + @"\eula.txt";
                    IniParser parser = new IniParser(strPathToRead);
                    parser.AddSetting("ROOT", "eula", "true");
                    parser.SaveSettings(this.ServerDirectory + @"\eula.txt", "#Minecraft EULA file\r\n#Generated by YAMS " + DateTime.Now.ToString() + "\r\n");
                }
                
                this.Start();
            }
        }
Пример #18
0
 void Command(Player pl, string cmd, string[] args)
 {
     if (cmd == "flag")
     {
         if (pl.Admin || API.HasFlag(pl, "canflag"))
         {
             pl.Notice("⚑", "FlagsAPI brought by ice cold", 20f);
             pl.MessageFrom(Name, "FlagsAPI 1.1 by ice cold");
             pl.MessageFrom(Name, "/flag_add Player flagname - gives the player the flagname");
             pl.MessageFrom(Name, "/flag_invoke Player flagname - removes the flag in player");
             pl.MessageFrom(Name, "/flag_register Flagname - register a new flag");
         }
         else
         {
             pl.MessageFrom(Name, "You dont have the > canflag < flag");
         }
     }
     else if (cmd == "flag_add")
     {
         if (pl.Admin || API.HasFlag(pl, "canflag"))
         {
             if (args.Length != 2)
             {
                 pl.Notice("⚑", "Syntax /flag_add PlayerName FlagName");
                 return;
             }
             if (list.ContainsSetting("Flags", args[1]))
             {
                 var user = Fougerite.Server.GetServer().FindPlayer(args[0]);
                 if (user == null)
                 {
                     pl.Notice("⚑", "Failed to find user"); return;
                 }
                 ini.AddSetting(user.SteamID, args[1], args[1]);
                 ini.Save();
                 pl.Notice("⚑", "You have given " + user.Name + " flag (" + args[1] + ")", 20f);
                 user.Notice("⚑", "You have received  flag (" + args[1] + ")", 20f);
             }
             else
             {
                 pl.MessageFrom(Name, "You must register this flag first by doing /flag_register " + args[1]);
             }
         }
     }
     else if (cmd == "flag_invoke")
     {
         if (pl.Admin || API.HasFlag(pl, "canflag"))
         {
             if (args.Length != 2)
             {
                 pl.Notice("⚑", "Syntax /flag_invoke PlayerName FlagName");
                 return;
             }
             var user = Fougerite.Server.GetServer().FindPlayer(args[0]);
             if (user == null)
             {
                 pl.Notice("⚑", "Failed to find user"); return;
             }
             if (ini.ContainsSetting(user.SteamID, args[1]))
             {
                 ini.DeleteSetting(user.SteamID, args[1]);
                 ini.Save();
                 pl.Notice("⚑", user.Name + " has no longer the flag " + args[1]);
             }
             else
             {
                 pl.Notice("⚑", user.Name + " doesn't have this flag");
             }
         }
     }
     else if (cmd == "flags_reload")
     {
         if (pl.Admin || API.HasFlag(pl, "canflag"))
         {
             ini  = new IniParser(Path.Combine(ModuleFolder, "PlayerFlagdb.ini"));
             list = new IniParser(Path.Combine(ModuleFolder, "Flags.list"));
             pl.Notice("Flags database reloaded");
         }
     }
     else if (cmd == "flag_register")
     {
         if (pl.Admin || API.HasFlag(pl, "canflag"))
         {
             API.RegisterFlag(args[0]);
             pl.MessageFrom(Name, "The flag (" + args[0] + ") was succestfully registered");
         }
     }
 }
Пример #19
0
 private void changeLanguageResolution()
 {
     parserSettings.AddSetting("Language", "Default", language.Text);
     //parserSettings.AddSetting("Options", "Resolution", resolution.SelectedIndex.ToString());
     parserSettings.SaveSettings();
 }
Пример #20
0
 public void CreateDefaultSettingsFile()
 {
     StreamWriter writer = new StreamWriter(m_settingsPath);
     writer.Close();
     IniParser iniParser = new IniParser(m_settingsPath);
     iniParser.AddSetting("NewTaskHotkey", "Ctrl", "false");
     iniParser.AddSetting("NewTaskHotkey", "Alt", "true");
     iniParser.AddSetting("NewTaskHotkey", "Win", "false");
     iniParser.AddSetting("NewTaskHotkey", "Shift", "false");
     iniParser.AddSetting("NewTaskHotkey", "Key", "N");
     iniParser.AddSetting("General", "startwithwindows", "true");
     iniParser.AddSetting("General", "autoupdate", "true");
     iniParser.AddSetting("General", "playsound", "true");
     iniParser.AddSetting("CultureInfo", "name", "lt-Lt");
     iniParser.AddSetting("RemindMeLater", "Default", RemindLaterValue.Round(10.0m/60.0m).ToString());
     iniParser.AddSetting("Skin", "code", BlackSkin.SKIN_UNIQUE_CODE);
     iniParser.AddSetting("Skin", "themename", _defaultThemeName);
     iniParser.AddSetting("Sync", "enable", "false");
     iniParser.AddSetting("Sync", "ID", "");
     iniParser.AddSetting("Sync", "interval", "30");
     iniParser.SaveSettings();
     m_log.Info("New settings file was created successfully");
 }
Пример #21
0
        static void Main(string[] args)
        {
            byte[]     byteBuff = new byte[256];
            byte[]     cmdx     = new byte[1];
            byte[]     len      = new byte[1];
            const byte INIT_TAB = 0x00;
            byte       retVal;

            byte[] byteRdBuff  = new byte[256];
            byte[] byteRddBuff = new byte[256];
            int    count       = 256;

            string[]  cmPort;
            int       pos, pIndex = 0;
            IniParser ini_file;
            string    sComPort;
            int       speed;
            //System.Timers.Timer myTimer = new System.Timers.Timer();
            StopWatch   sTimer;
            SerialQueue Q = new SerialQueue();

            //IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;
            //HwndSource src = HwndSource.FromHwnd(windowHandle);
            //src.AddHook(new HwndSourceHook(WndProc));

            // Starts library
            fixed_lib.lStart();

            for (int i = 0; i < 256; i++)
            {
                Q.PushRxByte((byte)i);
                byteBuff[i] = (byte)(i);
                //System.Console.WriteLine("bytes={0}\r\n",Q.PullRxByte());
            }

            // Initialize tag by passing first argument as zero
            fixed_lib.lPushTag(INIT_TAB, ref byteBuff, 0);
            fixed_lib.lPushTag(0xf, ref byteBuff, 0);
            fixed_lib.TransmitTag();
            fixed_lib.WaitTag(1000);

            do
            {
                retVal = fixed_lib.lPullTag(ref cmdx, ref len, ref byteBuff);
                if (retVal > 0)
                {
                    System.Console.WriteLine("cmdx={0} len={1}\r\n", cmdx[0], len[0]);
                }
            }while(retVal > 0);
            //

            fixed_lib.lStop();

            return;

            myTimer          = new System.Timers.Timer();
            myTimer.Elapsed += OnTimedEvent;
            myTimer.Interval = 10;
            myTimer.Enabled  = false;



            for (int i = 0; i < 256; i++)
            {
                Q.PushRxByte((byte)i);
                byteBuff[i] = (byte)(i + 10);
                //System.Console.WriteLine("bytes={0}\r\n",Q.PullRxByte());
            }

            //System.Console.WriteLine("-----------------------------\r\n");
            //Q.PullRx(byteRddBuff,80);
            //System.Console.WriteLine(ByteArrayToHexString(byteRddBuff));
            //Serial_Comm.encodeATEMsg(100,ref byteBuff,10);
            //return;


            const string iniFileName = @"serial.ini";

            using (StreamWriter w = File.AppendText(iniFileName));
            ini_file = new IniParser(iniFileName);

            sTimer = new StopWatch();
            sTimer.Start();

            ini_file.AddSetting("PORTSETTINGS", "COM", "1");
            ini_file.AddSetting("PORTSETTINGS", "SPEED", "115200");

            ini_file.SaveSettings();

            sComPort = ini_file.GetSetting("PORTSETTINGS", "COM");

            System.Console.WriteLine(args.Length);

            cmPort = SerialPort.GetPortNames();
            if (cmPort.Length == 0)
            {
                System.Console.WriteLine("No Serial Port Found");
            }
            else
            {
                System.Console.Write("One COM PORT found on system");
                System.Console.Write("Serial Port={0}", cmPort[0]);

                myTimer.Start();
            }

            Thread.Sleep(10000);
            Thread.Sleep(10000);
            Thread.Sleep(10000);
            Thread.Sleep(10000);


            StdOut.WriteLine("This is Main program\r\n");
            StdOut.WriteLine("This is Main program\r\n");
            StdOut.WriteLine("This is Main program\r\n");
            StdOut.WriteLine("This is Main program\r\n");
            StdOut.WriteLine("This is Main program\r\n");

            sTimer.Stop();
            StdOut.WriteLine("StopWatch Timer Val={0}\r\n", sTimer.GetElapsedTime());

            ini_file.SaveSettings();
        }
Пример #22
0
        public void ReloadConfig()
        {
            Loom.QueueOnMainThread(() =>
            {
                if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
                {
                    File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
                    Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));

                    Settings.AddSetting("Timer", "IntervalBetweenMessages_seconds", "60");
                    Settings.AddSetting("ChatMessages", "ShowInChat", "true");
                    Settings.AddSetting("PopupMessages", "ShowInPopup", "true");
                    Settings.AddSetting("PopupMessages", "PopupIcon", "X");
                    Settings.AddSetting("PopupMessages", "DurationPopup_secs", "10");

                    Settings.Save();
                    Logger.LogError(Name + "... New Settings File Created!");
                    ReloadConfig();
                    return;
                }
                else
                {
                    Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                    if (Settings.ContainsSetting("Timer", "IntervalBetweenMessages_seconds") &&
                        Settings.ContainsSetting("ChatMessages", "ShowInChat") &&
                        Settings.ContainsSetting("PopupMessages", "ShowInPopup") &&
                        Settings.ContainsSetting("PopupMessages", "PopupIcon") &&
                        Settings.ContainsSetting("PopupMessages", "DurationPopup_secs"))
                    {
                        try
                        {
                            IntervalSeconds = int.Parse(Settings.GetSetting("Timer", "IntervalBetweenMessages_seconds"));
                            chat            = Settings.GetBoolSetting("ChatMessages", "ShowInChat");
                            popup           = Settings.GetBoolSetting("PopupMessages", "ShowInPopup");
                            popupicon       = Settings.GetSetting("PopupMessages", "PopupIcon");
                            popupduration   = int.Parse(Settings.GetSetting("PopupMessages", "DurationPopup_secs"));
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError(Name + "... Detected a problem in the configuration");
                            Logger.LogError("ERROR -->" + ex.Message);
                            File.Delete(Path.Combine(ModuleFolder, "Settings.ini"));
                            Logger.LogError(Name + "... Deleted the old configuration file");
                            ReloadConfig();
                            return;
                        }
                    }
                    else
                    {
                        Logger.LogError(Name + "... Detected a problem in the configuration (lost key)");
                        File.Delete(Path.Combine(ModuleFolder, "Settings.ini"));
                        Logger.LogError(Name + "... Deleted the old configuration file");
                        ReloadConfig();
                        return;
                    }
                }

                if (!File.Exists(rutatxt))
                {
                    File.Create(rutatxt).Dispose();
                    StreamWriter WF = File.AppendText(rutatxt);
                    WF.WriteLine("[color red] Hello... this is message 1");
                    WF.WriteLine("[color blue] Hello... this is message 2");
                    WF.WriteLine("[color green] Hello... this is message 3");
                    WF.WriteLine("[color orange] Hello... this is message 4");
                    WF.WriteLine("[color yellow] Hello... this is message 5");
                    WF.WriteLine("Add more lines if you want ;)");
                    WF.Close();
                    Logger.LogError(Name + "... File not found (RandomMessages.txt) ,creating new one");
                    ReloadConfig();
                    return;
                }
                else
                {
                    if (File.ReadAllText(rutatxt).Length == 0)
                    {
                        Logger.LogError(Name + "... The File (RandomMessages.txt) dont contain any line or is empty...");
                        Logger.LogError(Name + "... You need to add at least one line so that the plugin works correctly");
                        msgs.Clear();
                        msgs.Add("The File (RandomMessages.txt) dont contain any line or is empty...");
                    }
                    else
                    {
                        msgs.Clear();
                        try
                        {
                            foreach (string str in File.ReadAllLines(rutatxt))
                            {
                                //if (str == string.Empty)
                                if (str.Length == 0)
                                {
                                    continue;
                                }
                                msgs.Add(str);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError(Name + "... The File (RandomMessages.txt) could not be read for any reason");
                        }
                    }
                }
                //Logger.Log(File.ReadAllText(rutatxt).Length.ToString());//comprobar si el archivo txt esta vacio
                return;
            });
        }
Пример #23
0
        private void ReloadConfig()
        {
            if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                Settings.AddSetting("Timer", "EnableAnnounce", "true");
                Settings.AddSetting("Timer", "AnnounceTimeMins", "5");
                Settings.AddSetting("Timer", "AnnounceMessage", "Commands: /web /discord /facebook /instagram /vk");

                Settings.AddSetting("Links", "Web", "http://fougerite.com/");
                Settings.AddSetting("Links", "Discord", "https://discord.gg/aw6N4pm");
                Settings.AddSetting("Links", "Facebook", "http://fougerite.com/");
                Settings.AddSetting("Links", "Instagram", "http://fougerite.com/");
                Settings.AddSetting("Links", "VKontakte", "http://fougerite.com/");

                Settings.AddSetting("ClientSide", "ClientMessage", "A new web browser has been opened");
                Settings.AddSetting("ClientSide", "MessageDuration", "15");
                Settings.Save();
                Logger.Log(Name + " Plugin: New Settings File Created!");
                ReloadConfig();
            }
            else
            {
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                if (Settings.ContainsSetting("Timer", "EnableAnnounce") &&
                    Settings.ContainsSetting("Timer", "AnnounceTimeMins") &&
                    Settings.ContainsSetting("Timer", "AnnounceMessage") &&

                    Settings.ContainsSetting("Links", "Web") &&
                    Settings.ContainsSetting("Links", "Discord") &&
                    Settings.ContainsSetting("Links", "Facebook") &&
                    Settings.ContainsSetting("Links", "Instagram") &&
                    Settings.ContainsSetting("Links", "VKontakte") &&

                    Settings.ContainsSetting("ClientSide", "ClientMessage") &&
                    Settings.ContainsSetting("ClientSide", "MessageDuration"))
                {
                    try
                    {
                        EnableAnnounce   = Settings.GetBoolSetting("Timer", "EnableAnnounce");
                        AnnounceTimeMins = int.Parse(Settings.GetSetting("Timer", "AnnounceTimeMins"));
                        AnnounceMessage  = Settings.GetSetting("Timer", "AnnounceMessage");

                        Web       = Settings.GetSetting("Links", "Web");
                        Discord   = Settings.GetSetting("Links", "Discord");
                        Facebook  = Settings.GetSetting("Links", "Facebook");
                        Instagram = Settings.GetSetting("Links", "Instagram");
                        VKontakte = Settings.GetSetting("Links", "VKontakte");

                        ClientMessage   = Settings.GetSetting("ClientSide", "ClientMessage");
                        MessageDuration = int.Parse(Settings.GetSetting("ClientSide", "MessageDuration"));

                        Logger.Log(Name + " Plugin: Settings file Loaded!");

                        if (EnableAnnounce)
                        {
                            Timer1(30 * 1000, null).Start();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(Name + " Plugin: Detected a problem in the configuration");
                        Logger.Log("ERROR -->" + ex.Message);
                        File.Delete(Path.Combine(ModuleFolder, "Settings.ini"));
                        Logger.Log(Name + " Plugin: Deleted the old configuration file");
                        ReloadConfig();
                    }
                }
                else
                {
                    Logger.LogError(Name + " Plugin: Detected a problem in the configuration (lost key)");
                    File.Delete(Path.Combine(ModuleFolder, "Settings.ini"));
                    Logger.LogError(Name + " Plugin: Deleted the old configuration file");
                    ReloadConfig();
                }
                return;
            }
        }
Пример #24
0
 public static void Set(string name, bool value)
 {
     Config.AddSetting(IniParser.RootSection, name, value);
 }
Пример #25
0
        void CheckConfig()
        {
            if (!File.Exists(Path.Combine(ModuleFolder, "BattleRoyale.ini")))
            {
                Logger.LogWarning("[BattleRoyale Beta 1] BattleRoyale.ini not found... creating one now");
                File.Create(Path.Combine(ModuleFolder, "BattleRoyale.ini")).Dispose();
                ini = new IniParser(Path.Combine(ModuleFolder, "BattleRoyale.ini"));
                ini.AddSetting("Options", "BattleTimer", BattleTimer.ToString());
                ini.AddSetting("Options", "npcgod", npcgod.ToString());
                ini.AddSetting("Options", "WaitTimer", WaitTimer.ToString());
                ini.AddSetting("Options", "MinPlayers", MinPlayers.ToString());
                ini.AddSetting("Options", "BarricadePlus", BarricadePlus.ToString());
                ini.AddSetting("Messages", "StartMessage", StartMessage.ToString());
                ini.AddSetting("Messages", "DeathMessage", DeathMessage.ToString());
                ini.AddSetting("Messages", "WinnerMessage", WinnerMessage.ToString());
                ini.AddSetting("Messages", "EndMessage", EndMessage.ToString());
                ini.AddSetting("Messages", "StartNotice", StartNotice.ToString());
                ini.AddSetting("Messages", "WinnerNotice", WinnerNotice.ToString());
                ini.AddSetting("Messages", "NotEnoughPlayersMessage", NotEnoughPlayersMessage.ToString());
                ini.AddSetting("Messages", "StartStartTimer", StartStartTimer.ToString());
                ini.AddSetting("Messages", "WaitMessage", WaitMessage.ToString());
                ini.AddSetting("Messages", "JoinMessage", JoinMessage.ToString());
                ini.AddSetting("Messages", "LeaveMessage", LeaveMessage.ToString());
                ini.AddSetting("Items", "Rock", "1");
                ini.AddSetting("Items", "Torch", "1");
                ini.AddSetting("Items", "Bandage", "1");
                ini.AddSetting("LootSpawn", "M4", "1");
                ini.AddSetting("LootSpawn", "Large Medkit", "5");

                ini.Save();
                Logger.Log("[BattleRoyale Beta 1] File created");
            }
            else
            {
                Logger.Log("[BattleRoyale Beta 1] Reading settings file......");
                ini                     = new IniParser(Path.Combine(ModuleFolder, "BattleRoyale.ini"));
                BattleTimer             = int.Parse(ini.GetSetting("Options", "BattleTimer"));
                npcgod                  = bool.Parse(ini.GetSetting("Options", "npcgod"));
                WaitTimer               = int.Parse(ini.GetSetting("Options", "WaitTimer"));
                MinPlayers              = int.Parse(ini.GetSetting("Options", "MinPlayers"));
                BarricadePlus           = bool.Parse(ini.GetSetting("Options", "BarricadePlus"));
                StartMessage            = ini.GetSetting("Messages", "StartMessage");
                DeathMessage            = ini.GetSetting("Messages", "DeathMessage");
                WinnerMessage           = ini.GetSetting("Messages", "WinnerMessage");
                EndMessage              = ini.GetSetting("Messages", "EndMessage");
                StartNotice             = ini.GetSetting("Messages", "StartNotice");
                WinnerNotice            = ini.GetSetting("Messages", "WinnerNotice");
                NotEnoughPlayersMessage = ini.GetSetting("Messages", "NotEnoughPlayersMessage");
                StartStartTimer         = ini.GetSetting("Messages", "StartStartTimer");
                WaitMessage             = ini.GetSetting("Messages", "WaitMessage");
                JoinMessage             = ini.GetSetting("Messages", "JoinMessage");
                LeaveMessage            = ini.GetSetting("Messages", "LeaveMessage");
            }
        }
Пример #26
0
 public void Command(User player, string cmd, string[] args)
 {
     if (cmd == "restartkit")
     {
         if (args.Length == 0)
         {
             player.MessageFrom(Name, aqua + "Usage /restartkit help");
             return;
         }
         if (args[0] == "help")
         {
             player.MessageFrom(Name, aqua + "Usage /restartkit kits = See all avaible kits");
             player.MessageFrom(Name, aqua + "Usage /restartkit receive kitname - Receive this kit (Only works when the admin gave you acces to it)");
             player.MessageFrom(Name, aqua + "usage /restartkit info kitname - see the kit items of a specific kit");
             if (player.Admin)
             {
                 player.MessageFrom(Name, "/restartkit_adduser player kitname - give the player acces to a kit");
             }
         }
         else if (args[0] == "info")
         {
             if (File.Exists(Path.Combine(defaultpath, args[1] + ".txt")))
             {
                 foreach (string xx in File.ReadAllLines(defaultpath + "\\" + args[1] + ".txt"))
                 {
                     string[] split = xx.Split(':');
                     string   one   = split[0];
                     string   two   = split[1];
                     if (one == "Message")
                     {
                         player.MessageFrom(Name, two);
                     }
                     else
                     {
                         player.MessageFrom(Name, $"{aqua}{two}x{one}");
                     }
                 }
             }
         }
         else if (args[0] == "kits")
         {
             player.MessageFrom(Name, aqua + "Avaible kits. Usage /restartkit receive kitname");
             foreach (string file in Directory.GetFiles(defaultpath))
             {
                 string name = file.Split('\\').Last();
                 player.MessageFrom(Name, $"{aqua} {name.Replace(".txt", string.Empty)}");
             }
         }
         else if (args[0] == "receive")
         {
             //util.Log("1");
             if (!users.ContainsSetting(args[1], player.SteamID))
             {
                 player.MessageFrom(Name, aqua + MessageBuyChat1); player.MessageFrom(Name, aqua + MessageBuyChat2); return;
             }
             //util.Log("2");
             if (AlreadyUsedKit(player, args))
             {
                 player.MessageFrom(Name, aqua + MessageAlready); player.MessageFrom(Name, aqua + MessageAlready1); return;
             }
             if (File.Exists(Path.Combine(defaultpath, args[1] + ".txt")))
             {
                 if (player.Inventory.FreeSlots == 0)
                 {
                     player.MessageFrom(Name, aqua + InventoryFull);
                     return;
                 }
                 // util.Log("2");
                 foreach (string xx in File.ReadAllLines(defaultpath + "\\" + args[1] + ".txt"))
                 {
                     string[] split = xx.Split(':');
                     string   one   = split[0];
                     //  util.Log("3");
                     string two = split[1];
                     if (one != "Message")
                     {
                         player.Inventory.AddItem(one, Convert.ToInt32(two));
                     }
                 }
                 player.MessageFrom(Name, aqua + MessageThanks);
                 StreamWriter writer = File.AppendText(path + player.SteamID + ".txt");
                 writer.WriteLine(args[1]);
                 writer.Close();
             }
         }
     }
     else if (cmd == "restartkit_adduser")
     {
         if (player.Admin)
         {
             if (args.Length == 2)
             {
                 User target = Server.GetServer().FindPlayer(args[0]);
                 users.AddSetting(args[1], target.SteamID, args[1]);
                 users.Save();
                 player.MessageFrom(Name, $"{aqua} You gave {args[1]} kit acces to {target.Name}");
             }
         }
     }
 }
Пример #27
0
        private void SaveHotkeys()
        {
            IniParser parser = new IniParser(IniFile);

            parser.AddSetting("Pitch", "IncreaseHotkey", pitchIncreaseHotkey.Text);
            parser.AddSetting("Pitch", "DecreaseHotkey", pitchDecreaseHotkey.Text);

            parser.AddSetting("Yaw", "IncreaseHotkey", yawIncreaseHotkey.Text);
            parser.AddSetting("Yaw", "DecreaseHotkey", yawDecreaseHotkey.Text);

            parser.AddSetting("Height", "IncreaseHotkey", cameraHeightIncreaseHotkey.Text);
            parser.AddSetting("Height", "DecreaseHotkey", cameraHeightDecreaseHotkey.Text);

            parser.AddSetting("Speed", "IncreaseHotkey", speedIncreaseHotkey.Text);
            parser.AddSetting("Speed", "DecreaseHotkey", speedDecreaseHotkey.Text);

            parser.AddSetting("ViewDistance", "IncreaseHotkey", drawDistanceIncreaseHotkey.Text);
            parser.AddSetting("ViewDistance", "DecreaseHotkey", drawDistanceDecreaseHotkey.Text);

            parser.AddSetting("RestoreDefaults", "Hotkey", restoreDefaultsHotkey.Text);

            parser.SaveSettings();
        }
Пример #28
0
 public void On_Command(Fougerite.Player player, string cmd, string[] args)
 {
     if (cmd == "wlist")
     {
         if (player.Admin || player.Moderator)
         {
             if (args.Length.Equals(0))
             {
                 player.MessageFrom("CountryBlackList", "Usage: /wlist <User Name>");
                 player.MessageFrom("CountryBlackList", "Adds a user to the whitelist");
             }
             else
             {
                 string           search = string.Join(" ", args);
                 Fougerite.Player target = Fougerite.Server.GetServer().FindPlayer(search);
                 if (target != null)
                 {
                     if (!OnWhiteList(player.SteamID, player.IP))
                     {
                         WhiteList.AddSetting(target.SteamID, target.IP, target.Name);
                         WhiteList.Save();
                         player.MessageFrom("CountryBlackList", "You have added " + target.Name + " to the whitelist");
                     }
                     else
                     {
                         player.MessageFrom("CountryBlackList", target.Name + " is already on the whitelist!");
                     }
                 }
             }
         }
         else
         {
             player.MessageFrom("CountryBlackList", "You are not allowed to use this command!");
         }
     }
     else if (cmd == "dlist")
     {
         if (player.Admin || player.Moderator)
         {
             if (args.Length.Equals(0))
             {
                 player.MessageFrom("CountryBlackList", "Usage: /dlist <User Name>");
                 player.MessageFrom("CountryBlackList", "Removes a user from the whitelist");
             }
             else
             {
                 string           search = string.Join(" ", args);
                 Fougerite.Player target = Fougerite.Server.GetServer().FindPlayer(search);
                 if (target != null)
                 {
                     if (OnWhiteList(player.SteamID, player.IP))
                     {
                         WhiteList.DeleteSetting(target.SteamID, target.IP);
                         WhiteList.Save();
                         player.MessageFrom("CountryBlackList", "You have removed " + target.Name + " from the whitelist");
                     }
                     else
                     {
                         player.MessageFrom("CountryBlackList", target.Name + " is not on the whitelist!");
                     }
                 }
             }
         }
         else
         {
             player.MessageFrom("CountryBlackList", "You are not allowed to use this command!");
         }
     }
     else if (cmd == "cbreload")
     {
         if (player.Admin)
         {
             player.MessageFrom("CountryBlackList", "Reloading config...");
             ReloadConfig();
             player.MessageFrom("CountryBlackList", "Done");
         }
     }
 }
Пример #29
0
        public override void Initialize()
        {
            RustPP = new RustPPExtension();

            var AssetPath_ = "file:///";

            Caching.expirationDelay = 1;
            Caching.CleanCache();

            Hooks.OnModulesLoaded      += OnModulesLoaded;
            Hooks.OnPlayerConnected    += OnPlayerConnected;
            Hooks.OnPlayerDisconnected += OnPlayerDisconnected;
            Hooks.OnPlayerSpawned      += OnPlayerSpawned;
            Hooks.OnPlayerKilled       += OnPlayerKilled;
            Hooks.OnCommand            += OnCommand;

            #region Settings

            if (!File.Exists(Util.GetRootFolder() + "\\Save\\WorldEditorServer\\ClientSideAssets.txt"))
            {
                File.Create(Util.GetRootFolder() + "\\Save\\WorldEditorServer\\ClientSideAssets.txt").Dispose();
            }

            if (!File.Exists(Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Settings.ini"))
            {
                File.Create(Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Settings.ini").Dispose();
                SettingsParser = new IniParser(Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Settings.ini");
                SettingsParser.AddSetting("Settings", "AssetBundles");
                SettingsParser.AddSetting("Settings", "TimedSpawns");
                SettingsParser.AddSetting("Settings", "PerformanceLog", "false");
                SettingsParser.AddSetting("Settings", "BundlesToTransfer");
                SettingsParser.AddSetting("Settings", "BundleDownloadLink");
                SettingsParser.Save();
            }

            if (SettingsParser == null)
            {
                SettingsParser = new IniParser(Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Settings.ini");
            }

            #endregion

            #region AssetBundles

            var bundlesString = SettingsParser.GetSetting("Settings", "AssetBundles");
            if (!string.IsNullOrEmpty(bundlesString))
            {
                foreach (var bundle in bundlesString.Split(','))
                {
                    if (string.IsNullOrEmpty(bundle))
                    {
                        continue;
                    }

                    Bundles.Add(bundle + "|" + AssetPath_ + Util.GetRootFolder() + "\\Save\\WorldEditorServer\\" +
                                bundle + ".unity3d");
                }
            }

            #endregion

            PerformanceLog = SettingsParser.GetBoolSetting("Settings", "PerformanceLog");

            #region ZoneSpawnAndDestroy

            var s = SettingsParser.GetSetting("Settings", "ZoneSpawnAndDestroy");
            if (!string.IsNullOrEmpty(s))
            {
                var dasEntries = s.Split('|');
                foreach (var dasEntry in dasEntries)
                {
                    if (string.IsNullOrEmpty(dasEntry))
                    {
                        continue;
                    }
                    var     dasEntrySplitted = dasEntry.Split('/');
                    Vector3 location         = Utils.StringToVector3(dasEntrySplitted[0]);
                    int     secondsToDestroy = int.Parse(dasEntrySplitted[1]);
                    int     radius           = int.Parse(dasEntrySplitted[2]);
                    string  prefab           = dasEntrySplitted[3];

                    _zones.Add(new Zone(location, radius, secondsToDestroy, prefab));
                }
            }

            #endregion

//            var bundlesToTransferString = SettingsParser.GetSetting("Settings", "BundlesToTransfer");
//            if (!string.IsNullOrEmpty(bundlesToTransferString))
//            {
//                var bundlesToTransfer = bundlesToTransferString.Split(',');
//                foreach (var bundleToTransfer in bundlesToTransfer)
//                {
//                    if (string.IsNullOrEmpty(bundleToTransfer))
//                        continue;

//                    RustBuster2016Server.API.AddFileToDownload(new RBDownloadable("WorldEditor\\", Util.GetRootFolder() + "\\Save\\WorldEditorServer\\" + bundleToTransfer + ".unity3d"));
//                }
//            }

//            TODO: AutoSpawn
//            var autoSpawnString = SettingsParser.GetSetting("Settings", "AutoSpawn");
//            if (!string.IsNullOrEmpty(autoSpawnString))
//            {
//                _autoSpawnGameObject = new GameObject();
//                var spawnBehaviour = _autoSpawnGameObject.AddComponent<AutoSpawnBehaviour>();
//                Object.DontDestroyOnLoad(_autoSpawnGameObject);
//
//                foreach (var autoSpawnEntryString in autoSpawnString.Split('|'))
//                {
//                    if (string.IsNullOrEmpty(autoSpawnEntryString))
//                    {
//                        continue;
//                    }
//
//                    if (!autoSpawnEntryString.Contains("/"))
//                    {
//                        string[] autoSpawnEntrySplit = autoSpawnEntryString.Split(':');
//
//                        var seconds = float.Parse(autoSpawnEntrySplit[0]);
//                        var destroySeconds = float.Parse(autoSpawnEntrySplit[1]);
//                        var bundle = autoSpawnEntrySplit[2];
//                        var name = autoSpawnEntrySplit[3];
//
//                        var locationString = autoSpawnEntrySplit[4].Split(',');
//                        Vector3 location = new Vector3(float.Parse(locationString[0]), float.Parse(locationString[1]),
//                            float.Parse(locationString[2]));
//
//                        var rotationString = autoSpawnEntrySplit[5].Split(',');
//                        Quaternion rotation = new Quaternion(float.Parse(rotationString[0]),
//                            float.Parse(rotationString[1]),
//                            float.Parse(rotationString[2]), float.Parse(rotationString[3]));
//
//                        var sizeString = autoSpawnEntrySplit[6].Split(',');
//                        Vector3 size = new Vector3(float.Parse(sizeString[0]), float.Parse(sizeString[1]),
//                            float.Parse(sizeString[2]));
//
//                        spawnBehaviour.StartCoroutine(
//                            spawnBehaviour.WaitAndSpawn(new AutoSpawnManager.SpawnedObject(seconds, destroySeconds,
//                                name,
//                                bundle, location,
//                                rotation,
//                                size)));
//
//                        Logger.Log("[WorldEditor] Started AutoSpawn Coroutine for " + name);
//                    }
//                    else
//                    {
//                        List<AutoSpawnManager.SpawnedObject>
//                            objectsToSpawn = new List<AutoSpawnManager.SpawnedObject>();
//                        foreach (var multiEntry in autoSpawnEntryString.Split('/'))
//                        {
//                            string[] autoSpawnEntrySplit = multiEntry.Split(':');
//
//                            var seconds = float.Parse(autoSpawnEntrySplit[0]);
//                            var destroySeconds = float.Parse(autoSpawnEntrySplit[1]);
//                            var bundle = autoSpawnEntrySplit[2];
//                            var name = autoSpawnEntrySplit[3];
//
//                            var locationString = autoSpawnEntrySplit[4].Split(',');
//                            Vector3 location = new Vector3(float.Parse(locationString[0]),
//                                float.Parse(locationString[1]),
//                                float.Parse(locationString[2]));
//
//                            var rotationString = autoSpawnEntrySplit[5].Split(',');
//                            Quaternion rotation = new Quaternion(float.Parse(rotationString[0]),
//                                float.Parse(rotationString[1]),
//                                float.Parse(rotationString[2]), float.Parse(rotationString[3]));
//
//                            var sizeString = autoSpawnEntrySplit[6].Split(',');
//                            Vector3 size = new Vector3(float.Parse(sizeString[0]), float.Parse(sizeString[1]),
//                                float.Parse(sizeString[2]));
//
//                            objectsToSpawn.Add(new AutoSpawnManager.SpawnedObject(seconds, destroySeconds, name, bundle,
//                                location, rotation, size));
//                        }
//
//                        spawnBehaviour.StartCoroutine(spawnBehaviour.WaitAndSpawn(objectsToSpawn));
//
//                        Logger.Log("[WorldEditor] Started multi AutoSpawn Coroutine for " + objectsToSpawn.Count +
//                                   " objects");
//                    }
//                }
//            }

//            API.AddFileToDownload(new RBDownloadable("WorldEditor\\",
//                Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Settings.ini"));
//            API.AddFileToDownload(new RBDownloadable("WorldEditor\\",
//                Util.GetRootFolder() + "\\Save\\WorldEditorServer\\ClientSideAssets.txt"));
//            API.AddFileToDownload(new RBDownloadable("WorldEditor\\",
//                Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Splash.png"));
//            API.AddFileToDownload(new RBDownloadable("WorldEditor\\",
//                Util.GetRootFolder() + "\\Save\\WorldEditorServer\\Hud.png"));

            MainHolder = new GameObject();
            Handler    = MainHolder.AddComponent <LoadingHandler>();
            Object.DontDestroyOnLoad(MainHolder);
            try
            {
                Handler.StartCoroutine(Handler.LoadAsset());
            }
            catch (Exception ex)
            {
                Logger.LogError("Couroutine failed. " + ex);
            }

            if (_FoundRB)
            {
                API.OnRustBusterUserMessage += OnRustBusterUserMessage;
            }
        }
Пример #30
0
        public void SaveSettingsToFile()
        {
            IniParser parser = new IniParser(m_settingsPath);
            parser.DeleteSetting("NewTaskHotkey", "alt");
            parser.DeleteSetting("NewTaskHotkey", "ctrl");
            parser.DeleteSetting("NewTaskHotkey", "shift");
            parser.DeleteSetting("NewTaskHotkey", "win");
            parser.DeleteSetting("NewTaskHotkey", "key");
            parser.DeleteSetting("general", "startwithwindows");
            parser.DeleteSetting("general", "autoupdate");
            parser.DeleteSetting("general", "playsound");
            parser.DeleteSetting("CultureInfo", "name");
            parser.DeleteSetting("RemindMeLater", "default");
            parser.DeleteSetting("skin", "code");
            parser.DeleteSetting("skin", "themename");
            parser.DeleteSetting("sync", "id");
            parser.DeleteSetting("sync", "interval");
            parser.DeleteSetting("sync", "enable");

            parser.AddSetting("NewTaskHotkey", "alt", StaticData.Settings.NewTaskHotkey.Alt.ToString());
            parser.AddSetting("NewTaskHotkey", "ctrl", StaticData.Settings.NewTaskHotkey.Ctrl.ToString());
            parser.AddSetting("NewTaskHotkey", "shift", StaticData.Settings.NewTaskHotkey.Shift.ToString());
            parser.AddSetting("NewTaskHotkey", "win", StaticData.Settings.NewTaskHotkey.Win.ToString());
            parser.AddSetting("NewTaskHotkey", "key", StaticData.Settings.NewTaskHotkey.Key);

            parser.AddSetting("General", "startwithwindows", StaticData.Settings.StartWithWindows.ToString());
            parser.AddSetting("General", "autoupdate", StaticData.Settings.CheckUpdates.ToString());
            parser.AddSetting("General", "playsound", StaticData.Settings.PlaySound.ToString());
            parser.AddSetting("CultureInfo", "name", StaticData.Settings.CultureData.CultureInfo.Name.ToString());
            parser.AddSetting("RemindMeLater", "default", RemindLaterValue.Round(StaticData.Settings.RemindMeLaterDecimalValue).ToString());
            parser.AddSetting("skin", "code", StaticData.Settings.SkinsUniqueCodes.SelectedSkin);
            parser.AddSetting("skin", "themename", StaticData.Settings.ThemeUniqueCode);
            parser.AddSetting("sync", "id", StaticData.Settings.Sync.Id);
            parser.AddSetting("sync", "interval", StaticData.Settings.Sync.Interval.ToString());
            parser.AddSetting("sync", "enable", StaticData.Settings.Sync.Enable.ToString());

            parser.SaveSettings();
            m_log.Info("Settings were saved successfully");
        }
Пример #31
0
        public void OnRustBusterUserMessage(API.RustBusterUserAPI user, Message msgc)
        {
            if (msgc.PluginSender == "JianxianC")
            {
                Fougerite.Player player = user.Player;

                string[] spl = msgc.MessageByClient.Split('-');
                if (spl.Length != 3)
                {
                    return;
                }

                string evt      = spl[0];
                string username = spl[1];
                string password = spl[2];
                if (evt == "AuthMeLogin")
                {
                    if (!WaitingUsers.ContainsKey(player.UID))
                    {
                        player.MessageFrom("仙域授权", orange + "You are logged in already.");
                        msgc.ReturnMessage = "DisApproved";
                        return;
                    }
                    if (!Credentials.ContainsKey(player.UID))
                    {
                        player.MessageFrom("仙域授权", orange + "This steamid is not registered yet!");
                        player.MessageFrom("仙域授权", orange + "Type /authme register username password");
                        msgc.ReturnMessage = "DisApproved";
                        return;
                    }

                    Credential cred = Credentials[player.UID];
                    if (!string.Equals(cred.Username, username, StringComparison.CurrentCultureIgnoreCase))
                    {
                        player.MessageFrom("仙域授权", orange + "Invalid username!");
                        AuthLogger.Log(player.Name + " - " + player.SteamID + " - " + player.IP +
                                       " tried to login using: " + username);
                        msgc.ReturnMessage = "DisApproved";
                        return;
                    }

                    if (username.Length > 25 || password.Length > 25)
                    {
                        player.MessageFrom("仙域授权", orange + "Sorry, username and password length must be below 25.");
                        msgc.ReturnMessage = "DisApproved";
                        return;
                    }

                    if (cred.HashedPassword != SHA1Hash(password))
                    {
                        AuthLogger.Log(player.Name + " - " + player.SteamID + " - " + player.IP +
                                       " tried to login using: " + username);
                        player.MessageFrom("仙域授权", red + "Invalid password! Seek help here: " + yellow + " " + SocialSiteForHelp);
                        msgc.ReturnMessage = "DisApproved";
                    }
                    else
                    {
                        PrivilegeStorage storage = WaitingUsers[player.UID];
                        if (storage.WasAdmin)
                        {
                            player.ForceAdminOff(false);
                            player.PlayerClient.netUser.SetAdmin(true);
                        }

                        if (storage.WasModerator)
                        {
                            player.ForceModeratorOff(false);
                        }

                        WaitingUsers.Remove(player.UID);
                        DataStore.GetInstance().Remove("AuthMeLogin", player.UID);
                        uLink.NetworkView.Get(player.PlayerClient.networkView)
                        .RPC("DestroyFreezeAuthMe", player.NetworkPlayer);

                        foreach (var x in RestrictedCommands)
                        {
                            player.UnRestrictCommand(x);
                        }

                        AuthLogger.Log(player.Name + " - " + player.SteamID + " - " + player.IP + " logged in using: " +
                                       username);
                        player.MessageFrom("仙域授权", green + "Successfully logged in!");
                        msgc.ReturnMessage = "Approved";
                    }
                }
                else if (evt == "AuthMeRegister")
                {
                    if (Credentials.ContainsKey(player.UID))
                    {
                        player.MessageFrom("仙域授权",
                                           red + "This STEAMID is already protected using password authentication!");
                        msgc.ReturnMessage = "InvalidRegistration";
                        return;
                    }

                    if (username.ToLower() == "username" || password.ToLower() == "password")
                    {
                        player.MessageFrom("仙域授权", orange + "Type /authme register username password");
                        msgc.ReturnMessage = "InvalidRegistration";
                        return;
                    }

                    bool b  = Regex.IsMatch(username, @"^[a-zA-Z0-9_&@%!+<>]+$");
                    bool b2 = Regex.IsMatch(password, @"^[a-zA-Z0-9_&@%!+<>]+$");

                    if (!b || !b2)
                    {
                        player.MessageFrom("仙域授权", orange + "Sorry, no special characters or space! Only: a-zA-Z0-9_&@%!+<>");
                        msgc.ReturnMessage = "InvalidRegistration";
                        return;
                    }

                    if (username.Length > 25 || password.Length > 25)
                    {
                        player.MessageFrom("仙域授权", orange + "Sorry, username and password length must be below 25.");
                        msgc.ReturnMessage = "InvalidRegistration";
                        return;
                    }

                    string hash = SHA1Hash(password);
                    Auths.AddSetting("Login", player.SteamID, username.ToLower() + "---##---" + hash);
                    Auths.Save();
                    Credentials.Add(player.UID, new Credential(username.ToLower(), hash));
                    player.MessageFrom("仙域授权",
                                       orange + "You have registered with: " + username + " - " + password +
                                       " (Your console has this info now too.)");
                    player.SendConsoleMessage(orange + "You have registered with: " + username + " - " + password);
                    WaitingUsers.Remove(player.UID);
                    DataStore.GetInstance().Remove("AuthMeLogin", player.UID);
                    uLink.NetworkView.Get(player.PlayerClient.networkView)
                    .RPC("DestroyFreezeAuthMe", player.NetworkPlayer);

                    foreach (var x in RestrictedCommands)
                    {
                        player.UnRestrictCommand(x);
                    }

                    AuthLogger.Log(player.Name + " - " + player.SteamID + " - " + player.IP +
                                   " registered an account: " + username);
                    msgc.ReturnMessage = "ValidRegistration";
                }
            }
        }
Пример #32
0
        public void Command(User pl, string cmd, string[] args)
        {
            if(cmd == "esshelp")
            {
                pl.Message("Fougerite-Essentials " + Version + " by ice cold");
                pl.Message("/help - see all commands");
                pl.Message("/rules - see all the rules");
                pl.Message("/info - See info about this plugin");
                pl.Message("/friendhelp - See all information about the friends system");
                pl.Message("/sharehelp - See all help about the share system");
                if(EnableHome) { pl.Message("/home - See all help about the home system"); }
                if(EnableRemove) { pl.Message("/remove - Enables/disables remover tool"); }
                if(Enabletpr) { pl.Message("/tpr name - sends teleport request to that user"); pl.Message("/tpa - Accepts an teleport reqequest"); }
                if(EnableWarps) { pl.Message("/warphelp - See all the help for the warping system"); }
                if(pl.Admin || pl.Moderator)
                {
                    pl.Message("/prod - Shows the owner of the object you are looking at");
                    pl.Message("/country player - Shows from which country a player comes");
                    pl.Message("/download url filename - downloads that object and put it in the the Downloaded folder EXAMPLE: (/download http://myitem.com myitem.zip)");
                    pl.Message("/addnewspawn - adds a new spawns to the overwrite spawn list");
                }              
            }
            else if(cmd == "country")
            {
                if(pl.Admin || pl.Moderator)
                {
                    if(args.Length != 1) { pl.Message("Usage /country player"); return; }
                    User target = Server.GetServer().FindPlayer(args[0]);
                    if(target == null) { pl.Message("Couldn't find the target user"); return; }
                    string country = PlayerDatabase.GetSetting(target.SteamID, "Country");
                    pl.Message("[color #ffb90f]" + target.Name  + " is located from [color #c1ffc1]" + country);
                }
            }
            else if(cmd == "download")
            {
                if(pl.Admin)
                {
                    if(args.Length != 2) { pl.Message("Usage /download url filename - EXAMPLE: (/download http://myitem.com myitem.zip)"); return; }
                    using (WebClient web = new WebClient())
                    {
                        web.DownloadFileAsync(new Uri(args[0]), Util.GetRootFolder() + "\\Save\\Fougerite-Essentials\\Downloaded\\" + args[1]);
                        pl.Message("[color #00ced1]Downloading " + args[1] + " to downloaded folder");
                    }
                }
            }
            else if(cmd == "addnewspawn")
            {
                if(pl.Admin)
                {
                    if(EnableNewSpawns)
                    {
                        string[] c = SpawnsOverwrite.EnumSection("SpawnLocations");
                        string co = (Convert.ToInt32(c[c.Length - 1]) + 1).ToString();
                        SpawnsOverwrite.AddSetting("SpawnLocations", co, pl.Location.ToString());
                        SpawnsOverwrite.Save();
                    }                 
                }
            }
            else if(cmd == "warphelp")
            {
                pl.Message("Fougerite-Essentials WarpSystem by ice cold");
                pl.Message("/warp name - Warps you to that location");
                pl.Message("/warps - See all the current warps");
                if(pl.Admin)
                {
                    pl.Message("/warp_set Name");
                    pl.Message("/warp_remove Name");
                }
            }
            else if(cmd == "warp")
            {
                if(args.Length != 1) { pl.Message("Usage /warp name"); return; }
                if(Warps.ContainsSetting("Warps", args[0]))
                {
                    if (pl.Admin)
                    {
                        Vector3 loc = Util.GetUtil().ConvertStringToVector3(Warps.GetSetting("Warps", args[0]));
                        pl.TeleportTo(loc);
                        pl.Message("[color#00bfff]Warped to " + args[0]);
                    }
                    else
                    {
                        if(!warpcd.Contains(pl.UID))
                        {
                            var dict = new Dictionary<string, object>();
                            dict["pl"] = pl;
                            warpcd.Add(pl.UID);
                            Warpcooldown(WarpCooldown * 1000, dict).Start();
                            Warpdelaytimer(WarpDelay * 1000, dict).Start();
                            string message = WarpDelayMessage.Replace("{warpname}", args[0]);
                        }
                        else
                        {
                            pl.Message(WarpCooldownMessage);
                        }
                    }
                }             
            }
            else if(cmd == "warps")
            {
                pl.Message("WarpsList");
                string[] l = Warps.EnumSection("Warps");
                foreach(var num in l)
                {
                    pl.Message(num);
                }
            }
            else if(cmd == "warp_set")
            {
                if(pl.Admin)
                {
                    if(args.Length != 1) { pl.Message("Usage /warp_set Name"); return; }
                    if(Warps.ContainsSetting("Warps", args[0])) { pl.Message("There is already a warp with the name " + args[0]); return; }
                    Warps.AddSetting("Warps", args[0], pl.Location.ToString());
                    Warps.Save();
                    pl.Message("Warp saved");
                }
            }
            else if(cmd == "warp_remove")
            {
                if(pl.Admin)
                {
                    if(args.Length != 1) { pl.Message("Usage /warp_remove Name"); return; }
                    if(!Warps.ContainsSetting("Warps", args[0])) { pl.Message("There is no warp with the name " + args[0]); return; }
                    Warps.DeleteSetting("Warps", args[0]);
                    Warps.Save();
                    pl.Message("The warp " + args[0] + " has been succesfully removed");
                }
            }
            else if(cmd == "help")
            {
                if(EnableHelp)
                {
                    foreach (var h in HelpList.EnumSection("Help"))
                    {
                        string d = HelpList.GetSetting("Help", h);
                        pl.MessageFrom("Help", d);
                    }
                }
                
            }
            else if(cmd == "rules")
            {
                if(EnableRules)
                {
                    foreach (var r in RulesList.EnumSection("Rules"))
                    {
                        string d = RulesList.GetSetting("Help", r);
                        pl.MessageFrom("Help", d);
                    }
                }          
            }
            else if(cmd == "info")
            {
                pl.MessageFrom(Name, "[color #87cefa][Fougerite-Essentials " + Version + " plugin brought by ice cold");
                pl.MessageFrom(Name, "[color #20b2aa]Wanna support ice cold? https://www.patreon.com/uberrust");
                pl.MessageFrom(Name, "[color #8470ff]You can download this plugin at ");
            }
            else if(cmd == "friendhelp")
            {
                pl.Message("[Fougerite-Essentials] Friends system brought by ice cold");
                pl.Message("/addfriend Name - ads player to your friends list");
                pl.Message("/unfriend Name - Unfriend someone");
                pl.Message("/friends - See all your friends");
            }
            else if(cmd == "sharehelp")
            {
                pl.Message("[Fougerite-Essentials] Share system brought by ice cold");
                pl.Message("/share Name - Door/structure share the player");
                pl.Message("/unshare Name - unshare someone");
                pl.Message("/sharelist - See all the people you have shared");
            }
            else if(cmd == "addfriend")
            {
                if(EnableFriendsSystem)
                {
                    if (args.Length != 1) { pl.Message("Usage /addfriend Name"); return; }
                    User target = Server.GetServer().FindPlayer(args[0]);
                    if (target == null) { pl.Message("Couldn't find the target user"); return; }
                    if (friends.ContainsSetting(pl.SteamID, target.SteamID)) { string message = AlreadyFriendedMessage.Replace("{friend}", target.Name); pl.Message(message); return; }
                    string me = AddFriendMessage.Replace("{friend}", target.Name);
                    pl.Message(me);
                    friends.AddSetting(pl.SteamID, target.SteamID, target.Name);
                    friends.Save();
                }
             
            }
            else if(cmd == "unfriend")
            {
                if(EnableShareSystem)
                {
                    if (args.Length != 1) { pl.Message("Usage /unfriend Name"); return; }
                    User target = Server.GetServer().FindPlayer(args[0]);
                    if(target == null) { pl.Message("Couldn't find the target user"); return; }
                    if(!friends.ContainsSetting(pl.SteamID, target.SteamID)) { pl.Message(target.Name + " Isnt in your friends list"); return; }
                    friends.DeleteSetting(pl.SteamID, target.SteamID);
                    friends.Save();
                    string message = UnfriendMessage.Replace("{target}", target.Name);
                    pl.Message(message);
                    friends.DeleteSetting(pl.SteamID, target.SteamID);
                    friends.Save();
                }
               
            }
            else if(cmd == "friends")
            {
                if(EnableFriendsSystem)
                {
                    pl.Message("===FriendsList===");
                    foreach (var id in friends.EnumSection(pl.SteamID))
                    {
                        string m = friends.GetSetting(pl.SteamID, id);
                        pl.Message("_ " + m);
                    }
                }
            }
            else if(cmd == "share")
            {
                if(EnableShareSystem)
                {
                    if(args.Length != 1) { pl.Message("Usage /share Name"); return; }
                    User target = Server.GetServer().FindPlayer(args[0]);
                    if (target == null) { pl.Message("Couldn't find the target user");  return; }
                    if(share.ContainsSetting(pl.SteamID, target.SteamID)) { string message = AlreadySharedMessage.Replace("{player}", target.Name); pl.Message(message); return; }
                    share.AddSetting(pl.SteamID, target.SteamID, target.Name);
                    share.Save();
                    string me = SharedMessage.Replace("{player}", target.Name);
                    pl.Message(me);
                }
            }
            else if(cmd == "unshare")
            {
                if(EnableShareSystem)
                {
                    if(args.Length != 1) { pl.Message("Usage /unshare Name"); return; }
                    User target = Server.GetServer().FindPlayer(args[0]);
                    if(target == null) { pl.Message("Couldn't find the target user"); return; }
                    if(!share.ContainsSetting(pl.SteamID, target.SteamID)) { pl.Message("You are not sharing with " + target.Name); return; }
                    share.DeleteSetting(pl.SteamID, target.SteamID);
                    share.Save();
                    string message = UnSharedMessage.Replace("{player}", target.Name);
                    pl.Message(message);
                }
            }
            else if(cmd == "sharelist")
            {
                if(EnableShareSystem)
                {
                    pl.Message("===ShareList===");
                    foreach(var id in share.EnumSection(pl.SteamID))
                    {
                        string m = share.GetSetting(pl.SteamID, id);
                        pl.Message("- " + m);
                    }
                }
            }
            else if(cmd == "prod")
            {
                if(pl.Admin || pl.Moderator)
                {
                    cachedCharacter = pl.PlayerClient.rootControllable.idMain.GetComponent<Character>();
                    if (!MeshBatchPhysics.Raycast(cachedCharacter.eyesRay, out cachedRaycast, out cachedBoolean, out cachedhitInstance)) { pl.Message("He Hello thats the sky bro"); return; }

                    if(cachedhitInstance != null)
                    {
                        cachedCollider = cachedhitInstance.physicalColliderReferenceOnly;
                        if (cachedCollider == null) { pl.Message("Sorry but i cannot prod that"); return; }
                        cachedStructure = cachedCollider.GetComponent<StructureComponent>();

                        if (cachedStructure != null && cachedStructure._master != null)
                        {
                            cachedMaster = cachedStructure._master;
                            var name = PlayerDatabase.GetSetting(cachedMaster.ownerID.ToString(), "Name");
                            pl.Message(string.Format("{object} - {ID} - {name}", cachedStructure.gameObject.name, cachedMaster.ownerID.ToString(), name == null ? "Unknown" : name.ToString()));
                        }
                    }
                    else
                    {

                        cachedDeployable = cachedRaycast.collider.GetComponent<DeployableObject>();

                        if(cachedDeployable != null)
                        {
                            var name = PlayerDatabase.GetSetting(cachedMaster.ownerID.ToString(), "Name");
                            pl.Message(string.Format("{object} - {ID} - {name}", cachedDeployable.gameObject.name, cachedDeployable.ownerID.ToString(), name == null ? cachedDeployable.ownerName.ToString() : name.ToString()));
                        }
                    }
                    pl.Message("Failed to prod " + cachedRaycast.collider.gameObject.name);
                }
            }
            else if(cmd == "home")
            {
                if(EnableHome)
                {
                    if(args.Length != 1)
                    {
                        pl.Message("[Fougerite-Essentials] Home system brought by ice cold");
                        if(!SleepingHome)
                        {
                            pl.Message("/home Name - teleports you the home");
                            pl.Message("/sethome Name - Enabled sethome mode (hit a foundation or ceiling to save your home)");
                            pl.Message("/delhome Name - Deletes that home");
                            pl.Message("/homes - Shows the list of homes");
                        }
                        else
                        {
                            pl.Message("/homeon - Enables home mode (place a Sleepingbag or Bed to save that as your current home)");
                            pl.Message("/gohome - Teleports you to your sleepingBag or Bed");
                        }
                    }
                    else
                    {
                        if(!SleepingHome)
                        {
                            if(!homecd.Contains(pl.UID))
                            {
                                if (StructureHome.ContainsSetting(pl.SteamID, args[0]))
                                {
                                    var homeloc = StructureHome.GetSetting(pl.SteamID, args[0]);
                                    var dict = new Dictionary<string, object>();
                                    dict["pl"] = pl;
                                    dict["homeloc"] = homeloc;
                                    HomeTimer(HomeDelay * 1000, dict).Start();
                                    string message = HomeDelayMessage.Replace("{home}", args[0]).Replace("{delay}", HomeDelay.ToString());
                                    pl.Message(message);
                                    HomeCooldown(HomeCooldown * 1000, dict).Start();
                                    homecd.Add(pl.UID);
                                }
                                else
                                {
                                    string message = NoHomeMessage.Replace("{home}", args[0]);
                                    pl.Message(message);
                                }
                            }
                            else
                            {
                                string message = HomeCooldownMessage.Replace("{cooldown}", HomeCooldown.ToString());
                                pl.Message(message);
                            }
                        }
                    }
                }
            }
            else if(cmd == "sethome")
            {
                if(EnableHome)
                {
                    if(!homemode.Contains(pl.UID))
                    {
                        if (args.Length != 1) { pl.Message("Usage /sethome Name"); return; }
                        string[] l = StructureHome.EnumSection(pl.SteamID);
                        if ((Convert.ToBoolean(l.Length == MaxHomes)))
                        {
                            pl.Message(MaxHomesMessage);
                        }
                        else
                        {
                            homemode.Add(pl.UID);
                            pl.Message("Sethome mode activated hit a foundation/ceiling to set your home");
                            homenum.Add(pl.UID, args[0]);
                        }
                    }
                    else
                    {
                        pl.Message("Please do /homestop first");
                    }
                  
                }
            }
            else if(cmd == "")
        }
Пример #33
0
        public void OnCommand(Fougerite.Player player, string cmd, string[] args)
        {
            if (cmd == "wipehelp")
            {
                if (player.Admin) // || player.Moderator ?
                {
                    player.MessageFrom("Wiper", "Wiper Commands:");
                    player.MessageFrom("Wiper", "/wipecheck - Checks for inactive objects");
                    player.MessageFrom("Wiper", "/wipereload - Reloads config.");
                    player.MessageFrom("Wiper", "/wipeid playerid - Wipes All the objects of the ID");
                    player.MessageFrom("Wiper", "/wipebarr - Deletes all barricades");
                    player.MessageFrom("Wiper", "/wipecampf - Deletes all camp fires");
                    player.MessageFrom("Wiper", "/wipeforced - Force a decay");
                    player.MessageFrom("Wiper", "/wipewl id - Adds ID to wipe whitelist.");
                }
            }
            else if (cmd == "wipecheck")
            {
                if (player.Admin)
                {
                    if (Broadcast)
                    {
                        Server.GetServer().BroadcastFrom("Wiper", "Checking for Wipeable unused objects....");
                    }
                    int[] obj = LaunchCheck();
                    if (Broadcast)
                    {
                        Server.GetServer().BroadcastFrom("Wiper", "Wiped " + obj[0] + " amount of objects, and " + obj[1] + " amount of user data.");
                    }
                    else
                    {
                        player.MessageFrom("Wiper", "Wiped " + obj[0] + " amount of objects, and " + obj[1] + " amount of user data.");
                    }
                }
            }
            else if (cmd == "wipereload")
            {
                if (player.Admin)
                {
                    bool b = ReloadConfig();
                    player.MessageFrom("Wiper", b ? "Done." : "Failed to reload config!");
                }
            }
            else if (cmd == "wipeid")
            {
                if (player.Admin)
                {
                    if (args.Length == 0)
                    {
                        player.MessageFrom("Wiper", "/wipeid playerid - Wipes All the objects of the ID");
                        return;
                    }
                    string id = args[0];
                    ulong  uid;
                    bool   b = ulong.TryParse(id, out uid);
                    if (!b)
                    {
                        player.MessageFrom("Wiper", "/wipeid playerid - Wipes All the objects of the ID");
                        return;
                    }
                    if (CollectedIDs.ContainsKey(uid))
                    {
                        CollectedIDs.Remove(uid);
                    }
                    int c = 0;
                    foreach (var x in World.GetWorld().Entities)
                    {
                        if (x.UOwnerID == uid)
                        {
                            x.Destroy();
                            c++;
                        }
                    }
                    System.IO.DirectoryInfo di = new DirectoryInfo(Path.Combine(Util.GetRootFolder(), UserDataPath + "\\" + id));
                    if (di.Exists)
                    {
                        foreach (FileInfo file in di.GetFiles())
                        {
                            file.Delete();
                        }
                        foreach (DirectoryInfo dir in di.GetDirectories())
                        {
                            dir.Delete(true);
                        }
                        di.Delete();
                    }
                    player.MessageFrom("Wiper", "Wiped: " + c + " objects.");
                }
            }
            else if (cmd == "wipebarr")
            {
                if (player.Admin)
                {
                    int c = 0;
                    foreach (var x in World.GetWorld().Entities)
                    {
                        if (x.Name.ToLower().Contains("barricade"))
                        {
                            x.Destroy();
                            c++;
                        }
                    }
                    player.MessageFrom("Wiper", "Wiped: " + c + " objects.");
                }
            }
            else if (cmd == "wipecampf")
            {
                if (player.Admin)
                {
                    int c = 0;
                    foreach (var x in World.GetWorld().Entities)
                    {
                        if (x.Name.ToLower().Contains("camp"))
                        {
                            x.Destroy();
                            c++;
                        }
                    }
                    player.MessageFrom("Wiper", "Wiped: " + c + " objects.");
                }
            }
            else if (cmd == "wipewl")
            {
                if (player.Admin)
                {
                    if (args.Length == 0)
                    {
                        player.MessageFrom("Wiper", "/wipewl playerid - Adds playerid to the whitelist.");
                        return;
                    }
                    string id = args[0];
                    ulong  uid;
                    bool   b = ulong.TryParse(id, out uid);
                    if (!b)
                    {
                        player.MessageFrom("Wiper", "/wipewl playerid - Adds playerid to the whitelist.");
                        return;
                    }

                    if (WList.Contains(uid))
                    {
                        player.MessageFrom("Wiper", "ID is already added!");
                        return;
                    }

                    WhiteList.AddSetting("WhiteList", id, "1");
                    WhiteList.Save();
                    player.MessageFrom("Wiper", "Added!");
                }
            }
            else if (cmd == "wipeall")
            {
                if (player.Admin)
                {
                    List <string> list = new List <string>();
                    int           c    = 0;
                    foreach (var x in World.GetWorld().Entities)
                    {
                        if (!list.Contains(x.OwnerID))
                        {
                            list.Add(x.OwnerID);
                        }
                        x.Destroy();
                    }

                    foreach (var id in list)
                    {
                        System.IO.DirectoryInfo di = new DirectoryInfo(Path.Combine(Util.GetRootFolder(), UserDataPath + "\\" + id));
                        if (di.Exists)
                        {
                            foreach (FileInfo file in di.GetFiles())
                            {
                                file.Delete();
                            }
                            foreach (DirectoryInfo dir in di.GetDirectories())
                            {
                                dir.Delete(true);
                            }
                            di.Delete();
                        }
                    }
                    player.MessageFrom("Wiper", "Wiped: " + c + " objects.");
                }
            }
        }
Пример #34
0
        public void On_PluginInit()
        {
            Author  = "Corrosion X";
            Version = "1.0.5";
            About   = "Requires players to accept rules or be disconnected.";
            ServerConsoleCommands.Register("kick.player")
            .setCallback(Kickplayer)
            .setDescription("Kicks player if they disagree to rules.")
            .setUsage("None");
            if (!Plugin.IniExists("rules"))
            {
                IniParser ini = Plugin.CreateIni("rules");
                ini.AddSetting("Rules", "1", "No Cheating.");
                ini.AddSetting("Rules", "2", "No Hacking.");
                ini.AddSetting("Rules", "3", "No Racism/Hate/Offensive text/symbols/images.");
                ini.Save();
            }
            IniParser getini = Plugin.GetIni("rules");

            ruleslist = "<color=white>Welcome to " + ConVar.Server.hostname + " !</color> \n <color=red>By joining this server you agree to the following rules:</color> \n \n";
            foreach (string arg in getini.EnumSection("Rules"))
            {
                ++i;
                ruleslist += "<color=white>" + i + "</color>" + ". <color=red>" + getini.GetSetting("Rules", arg) + "</color> \n";
            }
            json = @"[	
                        {
                            ""name"": ""AcceptRules"",
                            ""parent"": ""HUD/Overlay"",
                            ""components"":
                            [
                                {
                                     ""type"":""UnityEngine.UI.Image"",
                                     ""color"":""0.1 0.1 0.1 1"",
                                }, 
                                {    
                                    ""type"":""RectTransform"",
                                    ""anchormin"": ""0 0"",
                                    ""anchormax"": ""1 1""
                                },
                                {  
                                    ""type"":""NeedsCursor""
                                }
                            ]
                        },
                        {
                            ""parent"": ""AcceptRules"",
                            ""components"":
                            [
                                {
                                    ""type"":""UnityEngine.UI.Text"",
                                    ""text"":""{ruleslist}"",
                                    ""fontSize"":20,
                                    ""align"": ""MiddleCenter"",
                                },
                                { 
                                    ""type"":""RectTransform"",
                                    ""anchormin"": ""0 0.1"",
                                    ""anchormax"": ""1 0.9""
                                }
                            ]
                        }, 
                        {
                            ""name"": ""BtnAccept"",
                            ""parent"": ""AcceptRules"",
                            ""components"":
                            [
                                {
                                    ""type"":""UnityEngine.UI.Button"",
                                    ""close"":""AcceptRules"",
                                    ""color"": ""0.08 0.71 0.12 0.2"",
                                    ""imagetype"": ""Tiled""
                                },
                                {
                                    ""type"":""RectTransform"",
                                    ""anchormin"": ""0.2 0.16"",
                                    ""anchormax"": ""0.4 0.20""
                                }
                            ]
                        },
                        {
                            ""parent"": ""BtnAccept"",
                            ""components"":
                            [
                                {
                                    ""type"":""UnityEngine.UI.Text"",
                                    ""text"":""Accept"",
                                    ""fontSize"":20,
                                    ""align"": ""MiddleCenter""
                                }
                            ]
                        },
                        {
                            ""name"": ""BtnDontAccept"",
                            ""parent"": ""AcceptRules"",
                            ""components"":
                            [
                                {
                                    ""close"":""AcceptRules"",
                                    ""command"":""kick.player"",
                                    ""type"": ""UnityEngine.UI.Button"",
                                    ""color"": ""0.9 0.23 0.23 0.2"",
                                    ""imagetype"": ""Tiled""
                                },
                                {
                                    ""type"":""RectTransform"",
                                    ""anchormin"": ""0.6 0.16"",
                                    ""anchormax"": ""0.8 0.20""
                                }
                            ]
                        },
                        {
                            ""parent"": ""BtnDontAccept"",
                            ""components"":
                            [
                                {
                                    ""type"":""UnityEngine.UI.Text"",
                                    ""text"":""Dont Accept"",
                                    ""fontSize"":20,
                                    ""align"": ""MiddleCenter""
                                }
                            ]
                        }
                    ]";
        }
Пример #35
0
        public override void Initialize()
        {
            _inst = this;
            if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                Settings.AddSetting("Settings", "UseDayLimit", "True");
                Settings.AddSetting("Settings", "MaxDays", "14");
                Settings.AddSetting("Settings", "UseDecay", "False");
                Settings.AddSetting("Settings", "DecayTimer", "30");
                Settings.AddSetting("Settings", "WipeCheckTimer", "30");
                Settings.AddSetting("Settings", "Broadcast", "True");
                Settings.AddSetting("Settings", "UserDataPath", "\\rust_server_Data\\userdata\\");
                Settings.Save();
            }
            else
            {
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
            }
            if (!File.Exists(Path.Combine(ModuleFolder, "WhiteList.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "WhiteList.ini")).Dispose();
                WhiteList = new IniParser(Path.Combine(ModuleFolder, "WhiteList.ini"));
                WhiteList.AddSetting("WhiteList", "1234212312312", "1");
                WhiteList.Save();
            }
            if (!File.Exists(Path.Combine(ModuleFolder, "Players.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Players.ini")).Dispose();
                Check = true;
            }
            else
            {
                IniParser players = new IniParser(Path.Combine(ModuleFolder, "Players.ini"));
                string[]  enumm   = players.EnumSection("Objects");
                if (enumm.Length > 0)
                {
                    foreach (var x in enumm)
                    {
                        try
                        {
                            ulong  id   = ulong.Parse(x);
                            string date = players.GetSetting("Objects", x);
                            // dd/MM/yyyy
                            string[] spl = date.Split('/');
                            CollectedIDs[id] = new DateTime(int.Parse(spl[2]), int.Parse(spl[1]), int.Parse(spl[0]));
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError("[Wiper] Failed to parse datetime for " + x + " Error: " + ex);
                        }
                    }
                }
            }
            ReloadConfig();

            LoadDecayList();
            Fougerite.Hooks.OnCommand         += OnCommand;
            Fougerite.Hooks.OnPlayerConnected += OnPlayerConnected;
            Fougerite.Hooks.OnServerSaved     += OnServerSaved;
            Fougerite.Hooks.OnServerLoaded    += OnServerLoaded;
            GameO = new GameObject();
            GameO.AddComponent <WiperHandler>();
            UnityEngine.Object.DontDestroyOnLoad(GameO);
        }
Пример #36
0
        private void ReloadConfig()
        {
            weapons.Clear();
            if (!File.Exists(Path.Combine(ModuleFolder, "Settings.ini")))
            {
                File.Create(Path.Combine(ModuleFolder, "Settings.ini")).Dispose();
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));

                Settings.AddSetting("WeaponsCanShowDamage", "Rock", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "Stone Hatchet", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "Hatchet", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "Pick Axe", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "Hunting Bow", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "Uber Hunting Bow", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "Revolver", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "HandCannon", "false");
                Settings.AddSetting("WeaponsCanShowDamage", "Pipe Shotgun", "false");
                Settings.AddSetting("WeaponsCanShowDamage", "9mm Pistol", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "P250", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "MP5A4", "false");
                Settings.AddSetting("WeaponsCanShowDamage", "Shotgun", "false");
                Settings.AddSetting("WeaponsCanShowDamage", "M4", "false");
                Settings.AddSetting("WeaponsCanShowDamage", "Bolt Action Rifle", "true");
                Settings.AddSetting("WeaponsCanShowDamage", "F1 Grenade", "false");
                Settings.AddSetting("WeaponsCanShowDamage", "Explosive Charge", "true");
                Logger.Log(Name + " Plugin: New Settings File Created!");
                Settings.Save();
                ReloadConfig();
            }
            else
            {
                Settings = new IniParser(Path.Combine(ModuleFolder, "Settings.ini"));
                if (Settings.ContainsSetting("WeaponsCanShowDamage", "Rock") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Stone Hatchet") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Hatchet") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Pick Axe") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Hunting Bow") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Uber Hunting Bow") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Revolver") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "HandCannon") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Pipe Shotgun") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "9mm Pistol") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "P250") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "MP5A4") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Shotgun") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "M4") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Bolt Action Rifle") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "F1 Grenade") &&
                    Settings.ContainsSetting("WeaponsCanShowDamage", "Explosive Charge"))
                {
                    try
                    {
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Rock"))
                        {
                            weapons.Add("Rock");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Stone Hatchet"))
                        {
                            weapons.Add("Stone Hatchet");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Hatchet"))
                        {
                            weapons.Add("Hatchet");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Pick Axe"))
                        {
                            weapons.Add("Pick Axe");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Hunting Bow"))
                        {
                            weapons.Add("Hunting Bow");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Uber Hunting Bow"))
                        {
                            weapons.Add("Uber Hunting Bow");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Revolver"))
                        {
                            weapons.Add("Revolver");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "HandCannon"))
                        {
                            weapons.Add("HandCannon");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Pipe Shotgun"))
                        {
                            weapons.Add("Pipe Shotgun");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "9mm Pistol"))
                        {
                            weapons.Add("");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "P250"))
                        {
                            weapons.Add("P250");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "MP5A4"))
                        {
                            weapons.Add("MP5A4");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Shotgun"))
                        {
                            weapons.Add("Shotgun");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "M4"))
                        {
                            weapons.Add("M4");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Bolt Action Rifle"))
                        {
                            weapons.Add("Bolt Action Rifle");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "F1 Grenade"))
                        {
                            weapons.Add("F1 Grenade");
                        }
                        if (Settings.GetBoolSetting("WeaponsCanShowDamage", "Explosive Charge"))
                        {
                            weapons.Add("Explosive Charge");
                        }
                        Logger.Log(Name + " Plugin: Settings File Loaded!");
                    }
                    catch (Exception ex)
                    {
                        Logger.LogError(Name + " Plugin: Detected a problem in the configuration");
                        Logger.Log("ERROR -->" + ex.Message);
                        File.Delete(Path.Combine(ModuleFolder, "Settings.ini"));
                        Logger.LogError(Name + " Plugin: Deleted the old configuration file");
                        ReloadConfig();
                    }
                }
                else
                {
                    Logger.LogError(Name + " Plugin: Detected a problem in the configuration (lost key)");
                    File.Delete(Path.Combine(ModuleFolder, "Settings.ini"));
                    Logger.LogError(Name + " Plugin: Deleted the old configuration file");
                    ReloadConfig();
                }
                return;
            }
        }
Пример #37
0
        private void btSave_Click(object sender, EventArgs e)
        {
            if (!File.Exists(txExecutablePath.Text))
            {
                DialogResult = DialogResult.None;
                txExecutablePath.Focus();
                MessageBox.Show("Invalid witcher3.exe path", "failed to save.");
                return;
            }

            if (!File.Exists(txWCC_Lite.Text))
            {
                DialogResult = DialogResult.None;
                txWCC_Lite.Focus();
                MessageBox.Show("Invalid wcc_lite.exe path", "failed to save.");
                return;
            }
            var config = MainController.Get().Configuration;

            // Apply Theme
            bool applyTheme = config.ColorTheme != (EColorThemes)comboBoxTheme.SelectedItem;


            config.ExecutablePath = txExecutablePath.Text;
            config.WccLite        = txWCC_Lite.Text;
            config.TextLanguage   = txTextLanguage.Text;
            config.VoiceLanguage  = txVoiceLanguage.Text;
            config.ColorTheme     = (EColorThemes)comboBoxTheme.SelectedItem;
            config.Save();

            if (applyTheme)
            {
                MainController.Get().Window.GlobalApplyTheme();
            }


            try
            {
                IniParser ip = new IniParser(Path.Combine(MainController.Get().Configuration.GameRootDir, "bin\\config\\base\\general.ini"));
                if (!ip.HasSection("General") || ip.GetSetting("General", "DBGConsoleOn", true) != "true")
                {
                    if (MessageBox.Show(
                            "WolvenKit has detected that your game has the debug console disabled. It is a useful tool when testing mods. Would you like it to be enabled?",
                            "Debug console enabling", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        ip.AddSetting("General", "DBGConsoleOn", "true");
                        ip.Save();
                    }
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }

            try
            {
                using (var fs = new FileStream(txWCC_Lite.Text, FileMode.Open))
                    using (var bw = new BinaryWriter(fs))
                    {
                        var shawcc = SHA256.Create().ComputeHash(fs).Aggregate("", (c, n) => c += n.ToString("x2"));
                        switch (shawcc)
                        {
                        case wcc_sha256:
                        {
                            if (MessageBox.Show(@"wcc_lite is a great tool by CD Projekt red but
due to some internal problems they didn't really have time to properly develop it.
Due to this the tool takes an age to start up since it is searching for a CD Projekt red mssql server.
WolvenKit can patch this with a method figured out by blobbins on the witcher 3 forums.
Would you like to perform this patch?", "wcc_lite faster patch", MessageBoxButtons.YesNo, MessageBoxIcon.Question) ==
                                DialogResult.Yes)
                            {
                                //We perform the patch
                                bw.BaseStream.Seek(0x00713CD0, SeekOrigin.Begin);
                                bw.Write(new byte[0xDD].Select(x => x = 0x90).ToArray());
                            }
                            //Recompute hash
                            fs.Seek(0, SeekOrigin.Begin);
                            shawcc = SHA256.Create().ComputeHash(fs).Aggregate("", (c, n) => c += n.ToString("x2"));
                            if (shawcc == wcc_sha256_patched)
                            {
                                MessageBox.Show("Succesfully patched!", "Patch completed", MessageBoxButtons.OK,
                                                MessageBoxIcon.Information);
                            }
                            else
                            {
                                MessageBox.Show("Failed to patch! Please reinstall wcc_lite and try again", "Patch completed", MessageBoxButtons.OK,
                                                MessageBoxIcon.Error);
                            }
                            break;
                        }

                        case wcc_sha256_patched2:
                        case wcc_sha256_patched:
                        {
                            //Do nothing we are cool.
                            break;
                        }

                        default:
                        {
                            DialogResult = DialogResult.None;
                            txExecutablePath.Focus();
                            MessageBox.Show("Invalid wcc_lite.exe path you seem to have on older version", "failed to save.");
                            return;
                        }
                        }
                    }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
            }
        }
Пример #38
0
 public void Command(Player pl, string cmd, string[] args)
 {
     if (cmd == "tploc")
     {
         if (pl.Admin || Hasflag(pl, FLAG_USE))
         {
             if (args.Length == 0)
             {
                 pl.MessageFrom(Name, "Try out /tploc name");
                 string[] en = ini.EnumSection("Locations");
                 {
                     foreach (var locs in en)
                     {
                         pl.MessageFrom(Name, locs);
                     }
                 }
             }
             else
             {
                 if (ini.ContainsSetting("Locations", args[0]))
                 {
                     string  j   = ini.GetSetting("Locations", args[0]);
                     Vector3 loc = Util.GetUtil().ConvertStringToVector3(j); // makes a Vector3 of string
                     pl.TeleportTo(loc);
                     pl.InventoryNotice(args[0]);
                 }
                 else
                 {
                     pl.MessageFrom(Name, "There is no location called " + args[0]);
                 }
             }
         }
     }
     else if (cmd == "tplocadd")
     {
         if (pl.Admin || Hasflag(pl, FLAG_USE))
         {
             if (args.Length == 0)
             {
                 pl.MessageFrom(Name, "Syntax /tplocadd name");
                 return;
             }
             if (ini.ContainsSetting("Locations", args[0]))
             {
                 pl.MessageFrom(Name, "There is already a location called " + args[0]);
             }
             else
             {
                 ini.AddSetting("Locations", args[0], pl.Location.ToString());
                 pl.MessageFrom(Name, "New location called " + args[0] + " added at " + pl.Location);
                 ini.Save();
             }
         }
     }
     else if (cmd == "tplocremove")
     {
         if (pl.Admin || Hasflag(pl, FLAG_USE))
         {
             if (args.Length == 0)
             {
                 pl.MessageFrom(Name, "Syntax /tplocremove name");
                 return;
             }
             if (ini.ContainsSetting("Locations", args[0]))
             {
                 ini.DeleteSetting("Locations", args[0]);
                 ini.Save();
                 pl.MessageFrom(Name, "The location " + args[0] + " has been deleted");
             }
         }
     }
 }
Пример #39
0
        private void OnCommand(Fougerite.Player player, string cmd, string[] args)
        {
            switch (cmd)
            {
            case "record":
            {
                if (player.Admin || PermissionSystem.GetPermissionSystem().PlayerHasPermission(player, "recorder.record"))
                {
                    if (args.Length == 0)
                    {
                        player.MessageFrom("Recorder", "Usage: /record name");
                        return;
                    }

                    object state = DataStore.GetInstance().Get("Recorder", player.UID);
                    if (state != null)
                    {
                        player.MessageFrom("Recorder", "Already Recording!");
                        return;
                    }

                    string name = string.Join("_", args).ToLower();
                    DataStore.GetInstance().Flush("RecordedData" + player.UID);
                    DataStore.GetInstance().Add("Recorder", player.UID, 1);
                    DataStore.GetInstance().Add("Recorder_Name", player.UID, name);
                    player.MessageFrom("Recorder", "Recording " + name + ".ini (/rstop to finish!)");
                }

                break;
            }

            case "rspawn":
                if (player.Admin || PermissionSystem.GetPermissionSystem().PlayerHasPermission(player, "recorder.rspawn"))
                {
                    if (args.Length != 2)
                    {
                        player.MessageFrom("Recorder", "Usage: /rspawn name.ini distance");
                        return;
                    }

                    float distance = 0f;
                    bool  success  = float.TryParse(args[1], out distance);
                    if (!success)
                    {
                        player.MessageFrom("Recorder", "Usage: /rspawn name.ini distance");
                        return;
                    }

                    if (!File.Exists(Path.Combine(ModuleFolder, "Buildings\\" + args[0])))
                    {
                        player.MessageFrom("Recorder", "Building not found!");
                        return;
                    }

                    IniParser file = new IniParser(Path.Combine(ModuleFolder, "Buildings\\" + args[0]));

                    DataStore.GetInstance().Flush("SpawnedData" + player.UID);
                    DataStore.GetInstance().Remove("RecorderSMs", player.UID);

                    Vector3 playerFront    = Util.GetUtil().Infront(player, distance);
                    float   groundposition = World.GetWorld().GetGround(playerFront.x, playerFront.z);
                    //playerFront.y = World.GetGround(playerFront.x, playerFront.z);

                    List <string> sections = file.Sections.Where(x => x != "Init").ToList();

                    StructureMaster master   = null;
                    int             failures = 0;
                    for (int i = 0; i < sections.Count; i++)
                    {
                        Vector3 entPos = Util.GetUtil().CreateVector(float.Parse(file.GetSetting("Part" + i, "PosX")),
                                                                     float.Parse(file.GetSetting("Part" + i, "PosY")),
                                                                     float.Parse(file.GetSetting("Part" + i, "PosZ")));


                        Vector3 spawnPos = Util.GetUtil().CreateVector(entPos.x + playerFront.x, entPos.y + groundposition,
                                                                       entPos.z + playerFront.z);

                        Quaternion spawnRot = Util.GetUtil().CreateQuat(float.Parse(file.GetSetting("Part" + i, "RotX")),
                                                                        float.Parse(file.GetSetting("Part" + i, "RotY")),
                                                                        float.Parse(file.GetSetting("Part" + i, "RotZ")),
                                                                        float.Parse(file.GetSetting("Part" + i, "RotW")));


                        if (master == null)
                        {
                            master = World.GetWorld()
                                     .CreateSM(player, spawnPos.x, spawnPos.y, spawnPos.z, spawnRot);
                        }

                        Entity go = null;
                        try
                        {
                            go = World.GetWorld().SpawnEntity(file.GetSetting("Part" + i, "Prefab"), spawnPos,
                                                              spawnRot);
                        }
                        catch
                        {
                            failures++;
                            // Ignore.
                            continue;
                        }

                        try
                        {
                            if (go.IsLootableObject())
                            {
                                LootableObject lootableObject = (LootableObject)go.Object;
                                go.ChangeOwner(player);
                                DataStore.GetInstance().Add("SpawnedData" + player.UID, "Part" + i,
                                                            lootableObject.gameObject);
                            }
                            else if (go.IsDeployableObject())
                            {
                                go.ChangeOwner(player);
                                DeployableObject deployableObject = (DeployableObject)go.Object;

                                DataStore.GetInstance().Add("SpawnedData" + player.UID, "Part" + i,
                                                            deployableObject.gameObject);
                            }
                            else if (go.IsBasicDoor())
                            {
                                BasicDoor door = (BasicDoor)go.Object;
                                go.ChangeOwner(player);
                                DataStore.GetInstance().Add("SpawnedData" + player.UID, "Part",
                                                            door.gameObject);
                            }
                            else if (go.IsStructure())
                            {
                                StructureComponent structureComponent = (StructureComponent)go.Object;

                                master.AddStructureComponent(structureComponent);
                                DataStore.GetInstance().Add("SpawnedData" + player.UID, "Part" + i,
                                                            structureComponent.gameObject);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.LogError("[Recorder] Error: " + ex);
                            Logger.LogError("At prefab: " + file.GetSetting("Part" + i, "Prefab"));
                        }
                    }

                    player.MessageFrom("Recorder", args[0] + " was spawned !");
                    if (failures > 0)
                    {
                        player.MessageFrom("Recorder", failures + " amount of failures happened. This file might have wrong values!");
                    }
                }
                break;

            case "rlist":
                if (player.Admin || PermissionSystem.GetPermissionSystem().PlayerHasPermission(player, "recorder.rlist"))
                {
                    string[] files = Directory.GetFiles(Path.Combine(ModuleFolder, "Buildings\\"), "*.ini");

                    for (int i = 0; i < files.Length; i++)
                    {
                        files[i] = Path.GetFileName(files[i]);
                    }

                    player.MessageFrom("Recorder", "=== Files ===");
                    player.MessageFrom("Recorder", string.Join(", ", files));
                }

                break;

            case "rcancel":
                if (player.Admin || PermissionSystem.GetPermissionSystem().PlayerHasPermission(player, "recorder.rcancel"))
                {
                    int cpt = DataStore.GetInstance().Count("SpawnedData" + player.UID);
                    for (int i = 0; i < cpt; i++)
                    {
                        GameObject ent = DataStore.GetInstance().Get("SpawnedData" + player.UID, "Part" + i) as GameObject;
                        if (ent != null)
                        {
                            Util.GetUtil().DestroyObject(ent);
                        }
                        DataStore.GetInstance().Remove("Recorder", player.UID);
                        DataStore.GetInstance().Flush("RecordedData" + player.UID);
                        DataStore.GetInstance().Flush("SpawnedData" + player.UID);
                        DataStore.GetInstance().Remove("RecorderInit", player.UID);
                        DataStore.GetInstance().Remove("RecorderSMs", player.UID);
                    }

                    DataStore.GetInstance().Flush("SpawnedData" + player.UID);
                    player.Message("Cancelled recording");
                }
                break;

            case "rstop":
                if (player.Admin || PermissionSystem.GetPermissionSystem().PlayerHasPermission(player, "recorder.rstop"))
                {
                    string name = (string)DataStore.GetInstance().Get("Recorder_Name", player.UID);
                    if (File.Exists(Path.Combine(ModuleFolder, "Buildings\\" + name)))
                    {
                        var rnd  = new Random();
                        int rnd2 = rnd.Next(0, 500000);
                        player.Message(name + ".ini already exists ! renaming..");
                        name = name + rnd2;
                    }

                    name = name + ".ini";

                    Vector3 loc            = (Vector3)DataStore.GetInstance().Get("RecorderInit", player.UID);
                    float   groundposition = World.GetWorld().GetGround(loc.x, loc.z);
                    //loc.y = World.GetGround(loc.x, loc.z)

                    int cpt = DataStore.GetInstance().Count("RecordedData" + player.UID);
                    if (cpt == 0)
                    {
                        DataStore.GetInstance().Flush("RecordedData" + player.UID);
                        return;
                    }

                    if (!File.Exists(Path.Combine(ModuleFolder, "Buildings\\" + name)))
                    {
                        File.Create(Path.Combine(ModuleFolder, "Buildings\\" + name)).Dispose();
                    }
                    IniParser rfile = new IniParser(Path.Combine(ModuleFolder, "Buildings\\" + name));

                    for (int i = 0; i < cpt; i++)
                    {
                        Entity  ent    = (Entity)DataStore.GetInstance().Get("RecordedData" + player.UID, "Part" + i);
                        Vector3 entPos = new Vector3((ent.X - loc.x), (ent.Y - groundposition),
                                                     (ent.Z - loc.z));
                        Quaternion spawnRot = ent.Rotation;

                        rfile.AddSetting("Part" + i, "Prefab", Prefabs[ent.Name]);
                        rfile.AddSetting("Part" + i, "PosX", entPos.x.ToString(CultureInfo.CurrentCulture));
                        rfile.AddSetting("Part" + i, "PosY", entPos.y.ToString(CultureInfo.CurrentCulture));
                        rfile.AddSetting("Part" + i, "PosZ", entPos.z.ToString(CultureInfo.CurrentCulture));
                        rfile.AddSetting("Part" + i, "RotX", spawnRot.x.ToString(CultureInfo.CurrentCulture));
                        rfile.AddSetting("Part" + i, "RotY", spawnRot.y.ToString(CultureInfo.CurrentCulture));
                        rfile.AddSetting("Part" + i, "RotZ", spawnRot.z.ToString(CultureInfo.CurrentCulture));
                        rfile.AddSetting("Part" + i, "RotW", spawnRot.w.ToString(CultureInfo.CurrentCulture));
                    }

                    DataStore.GetInstance().Remove("Recorder", player.UID);
                    DataStore.GetInstance().Flush("RecordedData" + player.UID);
                    DataStore.GetInstance().Flush("SpawnedData" + player.UID);
                    DataStore.GetInstance().Remove("RecorderInit", player.UID);
                    DataStore.GetInstance().Remove("RecorderSMs", player.UID);
                    DataStore.GetInstance().Flush("SpawnedData" + player.UID);
                    rfile.Save();
                    player.MessageFrom("Recorder", name + " was saved !");
                }
                break;
            }
        }
Пример #40
0
        public void ToIni()
        {
            IniParser ini = new IniParser(path);

            ini.AddSetting("Def", "itemCount", itemCount.ToString());
            ini.AddSetting("Def", "ownerCanUse", OwnerUse.ToString());
            ini.AddSetting("Def", "modCanUse", ModeratorUse.ToString());
            ini.AddSetting("Def", "normalCanUse", NormalUse.ToString());

            for (int i = 0; i < itemCount; i++) {
                ini.AddSetting(i.ToString(), "Name", items[i].Name);
                ini.AddSetting(i.ToString(), "Amount", items[i].Amount.ToString());
            }

            ini.Save();
        }