MCLawl.Group.InitAll C# (CSharp) Method

InitAll() public static method

public static InitAll ( ) : void
return void
        public static void InitAll()
        {
            GroupList = new List<Group>();

            if (File.Exists("properties/ranks.properties"))
            {
                string[] lines = File.ReadAllLines("properties/ranks.properties");

                Group thisGroup = new Group();
                int gots = 0;

                foreach (string s in lines)
                {
                    try
                    {
                        if (s != "" && s[0] != '#')
                        {
                            if (s.Split('=').Length == 2)
                            {
                                string property = s.Split('=')[0].Trim();
                                string value = s.Split('=')[1].Trim();

                                if (thisGroup.name == "" && property.ToLower() != "rankname")
                                {
                                    Server.s.Log("Hitting an error at " + s + " of ranks.properties");
                                }
                                else
                                {
                                    switch (property.ToLower())
                                    {
                                        case "rankname":
                                            gots = 0;
                                            thisGroup = new Group();

                                            if (value.ToLower() == "developers" || value.ToLower() == "devs")
                                                Server.s.Log("You are not a developer. Stop pretending you are.");
                                            else if (GroupList.Find(grp => grp.name == value.ToLower()) == null)
                                                thisGroup.trueName = value;
                                            else
                                                Server.s.Log("Cannot add the rank " + value + " twice");
                                            break;
                                        case "permission":
                                            int foundPermission;

                                            try
                                            {
                                                foundPermission = int.Parse(value);
                                            }
                                            catch { Server.s.Log("Invalid permission on " + s); break; }

                                            if (thisGroup.Permission != LevelPermission.Null)
                                            {
                                                Server.s.Log("Setting permission again on " + s);
                                                gots--;
                                            }

                                            bool allowed = true;
                                            if (GroupList.Find(grp => grp.Permission == (LevelPermission)foundPermission) != null)
                                                allowed = false;

                                            if (foundPermission > 119 || foundPermission < -50)
                                            {
                                                Server.s.Log("Permission must be between -50 and 119 for ranks");
                                                break;
                                            }

                                            if (allowed)
                                            {
                                                gots++;
                                                thisGroup.Permission = (LevelPermission)foundPermission;
                                            }
                                            else
                                            {
                                                Server.s.Log("Cannot have 2 ranks set at permission level " + value);
                                            }
                                            break;
                                        case "limit":
                                            int foundLimit;

                                            try
                                            {
                                                foundLimit = int.Parse(value);
                                            }
                                            catch { Server.s.Log("Invalid limit on " + s); break; }

                                            gots++;
                                            thisGroup.maxBlocks = foundLimit;
                                            break;
                                        case "color":
                                            char foundChar;

                                            try
                                            {
                                                foundChar = char.Parse(value);
                                            }
                                            catch { Server.s.Log("Incorrect color on " + s); break; }

                                            if ((foundChar >= '0' && foundChar <= '9') || (foundChar >= 'a' && foundChar <= 'f'))
                                            {
                                                gots++;
                                                thisGroup.color = foundChar.ToString();
                                            }
                                            else
                                            {
                                                Server.s.Log("Invalid color code at " + s);
                                            }
                                            break;
                                        case "filename":
                                            if (value.Contains("\\") || value.Contains("/"))
                                            {
                                                Server.s.Log("Invalid filename on " + s);
                                                break;
                                            }

                                            gots++;
                                            thisGroup.fileName = value;
                                            break;
                                    }

                                    if (gots >= 4)
                                    {
                                        GroupList.Add(new Group(thisGroup.Permission, thisGroup.maxBlocks, thisGroup.trueName, thisGroup.color[0], thisGroup.fileName));
                                    }
                                }
                            }
                            else
                            {
                                Server.s.Log("In ranks.properties, the line " + s + " is wrongly formatted");
                            }
                        }
                    }
                    catch { }
                }
            }

            if (GroupList.Find(grp => grp.Permission == LevelPermission.Banned) == null) GroupList.Add(new Group(LevelPermission.Banned, 1, "Banned", '8', "banned.txt"));
            if (GroupList.Find(grp => grp.Permission == LevelPermission.Guest) == null) GroupList.Add(new Group(LevelPermission.Guest, 1, "Guest", '7', "guest.txt"));
            if (GroupList.Find(grp => grp.Permission == LevelPermission.Builder) == null) GroupList.Add(new Group(LevelPermission.Builder, 400, "Builder", '2', "builders.txt"));
            if (GroupList.Find(grp => grp.Permission == LevelPermission.AdvBuilder) == null) GroupList.Add(new Group(LevelPermission.AdvBuilder, 1200, "AdvBuilder", '3', "advbuilders.txt"));
            if (GroupList.Find(grp => grp.Permission == LevelPermission.Operator) == null) GroupList.Add(new Group(LevelPermission.Operator, 2500, "Operator", 'c', "operators.txt"));
            if (GroupList.Find(grp => grp.Permission == LevelPermission.Admin) == null) GroupList.Add(new Group(LevelPermission.Admin, 65536, "SuperOP", 'e', "uberOps.txt"));
            GroupList.Add(new Group(LevelPermission.Nobody, 65536, "Nobody", '0', "nobody.txt"));

            bool swap = true; Group storedGroup;
            while (swap)
            {
                swap = false;
                for (int i = 0; i < GroupList.Count - 1; i++)
                    if (GroupList[i].Permission > GroupList[i + 1].Permission)
                    {
                        swap = true;
                        storedGroup = GroupList[i];
                        GroupList[i] = GroupList[i + 1];
                        GroupList[i + 1] = storedGroup;
                    }
            }

            if (Group.Find(Server.defaultRank) != null) standard = Group.Find(Server.defaultRank);
            else standard = Group.findPerm(LevelPermission.Guest);

            foreach (Player pl in Player.players)
            {
                pl.group = GroupList.Find(g => g.name == pl.group.name);
            }

            saveGroups(GroupList);
        }

Usage Example

Ejemplo n.º 1
0
        public void Start()
        {
            shuttingDown = false;
            Log("Starting Server");

            if (!Directory.Exists("properties"))
            {
                Directory.CreateDirectory("properties");
            }
            if (!Directory.Exists("bots"))
            {
                Directory.CreateDirectory("bots");
            }
            if (!Directory.Exists("text"))
            {
                Directory.CreateDirectory("text");
            }

            if (!Directory.Exists("extra"))
            {
                Directory.CreateDirectory("extra");
            }
            if (!Directory.Exists("extra/undo"))
            {
                Directory.CreateDirectory("extra/undo");
            }
            if (!Directory.Exists("extra/undoPrevious"))
            {
                Directory.CreateDirectory("extra/undoPrevious");
            }
            if (!Directory.Exists("extra/copy/"))
            {
                Directory.CreateDirectory("extra/copy/");
            }
            if (!Directory.Exists("extra/copyBackup/"))
            {
                Directory.CreateDirectory("extra/copyBackup/");
            }

            try
            {
                if (File.Exists("server.properties"))
                {
                    File.Move("server.properties", "properties/server.properties");
                }
                if (File.Exists("rules.txt"))
                {
                    File.Move("rules.txt", "text/rules.txt");
                }
                if (File.Exists("welcome.txt"))
                {
                    File.Move("welcome.txt", "text/welcome.txt");
                }
                if (File.Exists("messages.txt"))
                {
                    File.Move("messages.txt", "text/messages.txt");
                }
                if (File.Exists("externalurl.txt"))
                {
                    File.Move("externalurl.txt", "text/externalurl.txt");
                }
                if (File.Exists("autoload.txt"))
                {
                    File.Move("autoload.txt", "text/autoload.txt");
                }
                if (File.Exists("IRC_Controllers.txt"))
                {
                    File.Move("IRC_Controllers.txt", "ranks/IRC_Controllers.txt");
                }
                if (Server.useWhitelist)
                {
                    if (File.Exists("whitelist.txt"))
                    {
                        File.Move("whitelist.txt", "ranks/whitelist.txt");
                    }
                }
            } catch { }

            Properties.Load("properties/server.properties");
            Updater.Load("properties/update.properties");

            Group.InitAll();
            Command.InitAll();
            GrpCommands.fillRanks();
            Block.SetBlocks();
            Awards.Load();

            if (File.Exists("text/emotelist.txt"))
            {
                foreach (string s in File.ReadAllLines("text/emotelist.txt"))
                {
                    Player.emoteList.Add(s);
                }
            }
            else
            {
                File.Create("text/emotelist.txt");
            }

            timeOnline = DateTime.Now;

            try
            {
                MySQL.executeQuery("CREATE DATABASE if not exists `" + MySQLDatabaseName + "`", true);
            }
            catch (Exception e)
            {
                Server.s.Log("MySQL settings have not been set! Please reference the MySQL_Setup.txt file on setting up MySQL!");
                Server.ErrorLog(e);
                //process.Kill();
                return;
            }

            MySQL.executeQuery("CREATE TABLE if not exists Players (ID MEDIUMINT not null auto_increment, Name VARCHAR(20), IP CHAR(15), FirstLogin DATETIME, LastLogin DATETIME, totalLogin MEDIUMINT, Title CHAR(20), TotalDeaths SMALLINT, Money MEDIUMINT UNSIGNED, totalBlocks BIGINT, totalKicked MEDIUMINT, color VARCHAR(6), title_color VARCHAR(6), PRIMARY KEY (ID));");

            // Check if the color column exists.
            DataTable colorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='color'");

            if (colorExists.Rows.Count == 0)
            {
                MySQL.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
            }
            colorExists.Dispose();

            // Check if the title color column exists.
            DataTable tcolorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='title_color'");

            if (tcolorExists.Rows.Count == 0)
            {
                MySQL.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
            }
            tcolorExists.Dispose();

            if (levels != null)
            {
                foreach (Level l in levels)
                {
                    l.Unload();
                }
            }
            ml.Queue(delegate
            {
                try
                {
                    levels = new List <Level>(Server.maps);
                    MapGen = new MapGenerator();

                    Random random = new Random();

                    if (File.Exists("levels/" + Server.level + ".lvl"))
                    {
                        mainLevel        = Level.Load(Server.level);
                        mainLevel.unload = false;
                        if (mainLevel == null)
                        {
                            if (File.Exists("levels/" + Server.level + ".lvl.backup"))
                            {
                                Log("Attempting to load backup.");
                                File.Copy("levels/" + Server.level + ".lvl.backup", "levels/" + Server.level + ".lvl", true);
                                mainLevel = Level.Load(Server.level);
                                if (mainLevel == null)
                                {
                                    Log("BACKUP FAILED!");
                                    Console.ReadLine(); return;
                                }
                            }
                            else
                            {
                                Log("mainlevel not found");
                                mainLevel = new Level(Server.level, 128, 64, 128, "flat");

                                mainLevel.permissionvisit = LevelPermission.Guest;
                                mainLevel.permissionbuild = LevelPermission.Guest;
                                mainLevel.Save();
                            }
                        }
                    }
                    else
                    {
                        Log("mainlevel not found");
                        mainLevel = new Level(Server.level, 128, 64, 128, "flat");

                        mainLevel.permissionvisit = LevelPermission.Guest;
                        mainLevel.permissionbuild = LevelPermission.Guest;
                        mainLevel.Save();
                    }
                    addLevel(mainLevel);
                    mainLevel.physThread.Start();
                } catch (Exception e) { Server.ErrorLog(e); }
            });

            ml.Queue(delegate
            {
                bannedIP       = PlayerList.Load("banned-ip.txt", null);
                ircControllers = PlayerList.Load("IRC_Controllers.txt", null);

                foreach (Group grp in Group.GroupList)
                {
                    grp.playerList = PlayerList.Load(grp.fileName, grp);
                }
                if (Server.useWhitelist)
                {
                    whiteList = PlayerList.Load("whitelist.txt", null);
                }
            });

            ml.Queue(delegate
            {
                if (File.Exists("text/autoload.txt"))
                {
                    try
                    {
                        string[] lines = File.ReadAllLines("text/autoload.txt");
                        foreach (string line in lines)
                        {
                            //int temp = 0;
                            string _line = line.Trim();
                            try
                            {
                                if (_line == "")
                                {
                                    continue;
                                }
                                if (_line[0] == '#')
                                {
                                    continue;
                                }
                                int index = _line.IndexOf("=");

                                string key = _line.Split('=')[0].Trim();
                                string value;
                                try
                                {
                                    value = _line.Split('=')[1].Trim();
                                }
                                catch
                                {
                                    value = "0";
                                }

                                if (!key.Equals(mainLevel.name))
                                {
                                    Command.all.Find("load").Use(null, key + " " + value);
                                    Level l = Level.FindExact(key);
                                }
                                else
                                {
                                    try
                                    {
                                        int temp = int.Parse(value);
                                        if (temp >= 0 && temp <= 3)
                                        {
                                            mainLevel.setPhysics(temp);
                                        }
                                    }
                                    catch
                                    {
                                        Server.s.Log("Physics variable invalid");
                                    }
                                }
                            }
                            catch
                            {
                                Server.s.Log(_line + " failed.");
                            }
                        }
                    }
                    catch
                    {
                        Server.s.Log("autoload.txt error");
                    }
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                else
                {
                    Log("autoload.txt does not exist");
                }
            });

            ml.Queue(delegate
            {
                Log("Creating listening socket on port " + Server.port + "... ");
                if (Setup())
                {
                    s.Log("Done.");
                }
                else
                {
                    s.Log("Could not create socket connection.  Shutting down.");
                    return;
                }
            });

            ml.Queue(delegate
            {
                updateTimer.Elapsed += delegate
                {
                    Player.GlobalUpdate();
                    PlayerBot.GlobalUpdatePosition();
                };

                updateTimer.Start();
            });


            // Heartbeat code here:

            ml.Queue(delegate
            {
                try
                {
                    Heartbeat.Init();
                }
                catch (Exception e)
                {
                    Server.ErrorLog(e);
                }
            });

            // END Heartbeat code

            /*
             * Thread processThread = new Thread(new ThreadStart(delegate
             * {
             *  try
             *  {
             *      PCCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
             *      ProcessCounter = new PerformanceCounter("Process", "% Processor Time", Process.GetCurrentProcess().ProcessName);
             *      PCCounter.BeginInit();
             *      ProcessCounter.BeginInit();
             *      PCCounter.NextValue();
             *      ProcessCounter.NextValue();
             *  }
             *  catch { }
             * }));
             * processThread.Start();
             */

            ml.Queue(delegate
            {
                messageTimer.Elapsed += delegate
                {
                    RandomMessage();
                };
                messageTimer.Start();

                process = System.Diagnostics.Process.GetCurrentProcess();

                if (File.Exists("text/messages.txt"))
                {
                    StreamReader r = File.OpenText("text/messages.txt");
                    while (!r.EndOfStream)
                    {
                        messages.Add(r.ReadLine());
                    }
                    r.Dispose();
                }
                else
                {
                    File.Create("text/messages.txt").Close();
                }

                if (Server.irc)
                {
                    new IRCBot();
                }


                //      string CheckName = "FROSTEDBUTTS";

                //       if (Server.name.IndexOf(CheckName.ToLower())!= -1){ Server.s.Log("FROSTEDBUTTS DETECTED");}
                new AutoSaver(Server.backupInterval);     //2 and a half mins

                blockThread = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(blockInterval * 1000);
                        foreach (Level l in levels)
                        {
                            l.saveChanges();
                        }
                    }
                }));
                blockThread.Start();

                locationChecker = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(3);
                        for (int i = 0; i < Player.players.Count; i++)
                        {
                            try
                            {
                                Player p = Player.players[i];

                                if (p.frozen)
                                {
                                    unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
                                }
                                else if (p.following != "")
                                {
                                    Player who = Player.Find(p.following);
                                    if (who == null || who.level != p.level)
                                    {
                                        p.following = "";
                                        if (!p.canBuild)
                                        {
                                            p.canBuild = true;
                                        }
                                        if (who != null && who.possess == p.name)
                                        {
                                            who.possess = "";
                                        }
                                        continue;
                                    }
                                    if (p.canBuild)
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                    else
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                }
                                else if (p.possess != "")
                                {
                                    Player who = Player.Find(p.possess);
                                    if (who == null || who.level != p.level)
                                    {
                                        p.possess = "";
                                    }
                                }

                                ushort x = (ushort)(p.pos[0] / 32);
                                ushort y = (ushort)(p.pos[1] / 32);
                                ushort z = (ushort)(p.pos[2] / 32);

                                if (p.level.Death)
                                {
                                    p.RealDeath(x, y, z);
                                }
                                p.CheckBlock(x, y, z);

                                p.oldBlock = (ushort)(x + y + z);
                            } catch (Exception e) { Server.ErrorLog(e); }
                        }
                    }
                }));

                locationChecker.Start();

                Log("Finished setting up server");
            });
        }