Ejemplo n.º 1
0
        public void Start()
        {
            shuttingDown = false;
            Log("Starting Server");
            {
                try
                {
                    if (File.Exists("Restarter.exe"))
                    {
                        File.Delete("Restarter.exe");
                    }
                }
                catch { }
                try
                {
                    if (File.Exists("Restarter.pdb"))
                    {
                        File.Delete("Restarter.pdb");
                    }
                }
                catch { }
            }
            if (!Directory.Exists("properties"))
            {
                Directory.CreateDirectory("properties");
            }
            if (!Directory.Exists("levels"))
            {
                Directory.CreateDirectory("levels");
            }
            if (!Directory.Exists("bots"))
            {
                Directory.CreateDirectory("bots");
            }
            if (!Directory.Exists("text"))
            {
                Directory.CreateDirectory("text");
            }
            if (!File.Exists("text/tempranks.txt"))
            {
                File.CreateText("text/tempranks.txt").Dispose();
            }
            if (!File.Exists("text/rankinfo.txt"))
            {
                File.CreateText("text/rankinfo.txt").Dispose();
            }
            if (!File.Exists("text/transexceptions.txt"))
            {
                File.CreateText("text/transexceptions.txt").Dispose();
            }
            if (!File.Exists("text/gcaccepted.txt"))
            {
                File.CreateText("text/gcaccepted.txt").Dispose();
            }
            if (!File.Exists("text/bans.txt"))
            {
                File.CreateText("text/bans.txt").Dispose();
            }
            else
            {
                string bantext = File.ReadAllText("text/bans.txt");
                if (!bantext.Contains("%20") && bantext != "")
                {
                    bantext = bantext.Replace("~", "%20");
                    bantext = bantext.Replace("-", "%20");
                    File.WriteAllText("text/bans.txt", bantext);
                }
            }



            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/");
            }
            if (!Directory.Exists("extra/Waypoints"))
            {
                Directory.CreateDirectory("extra/Waypoints");
            }

            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 (useWhitelist)
                {
                    if (File.Exists("whitelist.txt"))
                    {
                        File.Move("whitelist.txt", "ranks/whitelist.txt");
                    }
                }
            }
            catch { }

            if (File.Exists("text/custom$s.txt"))
            {
                using (StreamReader r = new StreamReader("text/custom$s.txt"))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        if (line.StartsWith("//"))
                        {
                            continue;
                        }
                        var split = line.Split(new[] { ':' }, 2);
                        if (split.Length == 2 && !String.IsNullOrEmpty(split[0]))
                        {
                            customdollars.Add(split[0], split[1]);
                        }
                    }
                }
            }
            else
            {
                s.Log("custom$s.txt does not exist, creating");
                using (StreamWriter SW = File.CreateText("text/custom$s.txt"))
                {
                    SW.WriteLine("// This is used to create custom $s");
                    SW.WriteLine("// If you start the line with a // it wont be used");
                    SW.WriteLine("// It should be formatted like this:");
                    SW.WriteLine("// $website:dekemaserv.com");
                    SW.WriteLine("// That would replace '$website' in any message to 'dekemaserv.com'");
                    SW.WriteLine("// It must not start with a // and it must not have a space between the 2 sides and the colon (:)");
                    SW.Close();
                }
            }

            LoadAllSettings();

            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").Dispose();
            }



            timeOnline = DateTime.Now;
            {
                try
                {
                    MySQL.executeQuery("CREATE DATABASE if not exists `" + MySQLDatabaseName + "`", true); // works in both now, SQLite simply ignores this.
                }
                catch (MySql.Data.MySqlClient.MySqlException e)
                {
                    Server.s.Log("MySQL settings have not been set! Many features will not be available if MySQL is not enabled");
                    Server.ErrorLog(e);
                }
                catch (Exception e)
                {
                    ErrorLog(e);
                    s.Log("MySQL settings have not been set! Please Setup using the properties window.");
                    process.Kill();
                    return;
                }
                MySQL.executeQuery(string.Format("CREATE TABLE if not exists Players (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Name VARCHAR(20), IP CHAR(15), FirstLogin DATETIME, LastLogin DATETIME, totalLogin MEDIUMINT, Title CHAR(20), TotalDeaths SMALLINT, Money MEDIUMINT UNSIGNED, totalBlocks BIGINT, totalCuboided BIGINT, totalKicked MEDIUMINT, TimeSpent VARCHAR(20), color VARCHAR(6), title_color VARCHAR(6){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : "")));
                MySQL.executeQuery(string.Format("CREATE TABLE if not exists Playercmds (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Time DATETIME, Name VARCHAR(20), Rank VARCHAR(20), Mapname VARCHAR(40), Cmd VARCHAR(40), Cmdmsg VARCHAR(40){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : "")));

                if (useMySQL)
                {
                    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();

                    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();

                    DataTable timespent = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='TimeSpent'");

                    if (timespent.Rows.Count == 0)
                    {
                        MySQL.executeQuery("ALTER TABLE Players ADD COLUMN TimeSpent VARCHAR(20) AFTER totalKicked"); //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN TimeSpent VARCHAR(20) AFTER totalKicked");
                    }
                    timespent.Dispose();

                    DataTable totalCuboided = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='totalCuboided'");

                    if (totalCuboided.Rows.Count == 0)
                    {
                        MySQL.executeQuery("ALTER TABLE Players ADD COLUMN totalCuboided BIGINT AFTER totalBlocks"); //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN totalCuboided BIGINT AFTER totalBlocks");
                    }
                    totalCuboided.Dispose();
                }
            }

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

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

                    addLevel(mainLevel);
                }
                catch (Exception e) { ErrorLog(e); }
            });
            ml.Queue(delegate
            {
                bannedIP       = PlayerList.Load("banned-ip.txt", null);
                ircControllers = PlayerList.Load("IRC_Controllers.txt", null);
                muted          = PlayerList.Load("muted.txt", null);

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

            ml.Queue(delegate
            {
                transignore.AddRange(File.ReadAllLines("text/transexceptions.txt"));
                if (File.Exists("text/autoload.txt"))
                {
                    try
                    {
                        string[] lines = File.ReadAllLines("text/autoload.txt");
                        foreach (string _line in lines.Select(line => line.Trim()))
                        {
                            try
                            {
                                if (_line == "")
                                {
                                    continue;
                                }
                                if (_line[0] == '#')
                                {
                                    continue;
                                }

                                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
                                    {
                                        s.Log("Physics variable invalid");
                                    }
                                }
                            }
                            catch
                            {
                                s.Log(_line + " failed.");
                            }
                        }
                    }
                    catch
                    {
                        s.Log("autoload.txt error");
                    }
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                else
                {
                    Log("autoload.txt does not exist");
                }
            });

            ml.Queue(delegate
            {
                foreach (string line in File.ReadAllLines("text/transexceptions.txt"))
                {
                    transignore.Add(line); //loading all playernames of people who turned off translation
                }
                foreach (string line in File.ReadAllLines("text/gcaccepted.txt"))
                {
                    gcaccepted.Add(line); //loading all playernames of people who turned off translation
                }
                Log("Creating listening socket on port " + port + "... ");
                Setup();
                //s.Log(Setup() ? "Done." : "Could not create socket connection. Shutting down.");
            });



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

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

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


                new AutoSaver(Server.backupInterval);

                blockThread = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(blockInterval * 1000);
                        levels.ForEach(delegate(Level l)
                        {
                            try
                            {
                                l.saveChanges();
                            }
                            catch (Exception e)
                            {
                                Server.ErrorLog(e);
                            }
                        });
                    }
                }));
                blockThread.Start();

                locationChecker = new Thread(new ThreadStart(delegate
                {
                    Player p, who;
                    ushort x, y, z;
                    int i;
                    while (true)
                    {
                        Thread.Sleep(3);
                        for (i = 0; i < Player.players.Count; i++)
                        {
                            try
                            {
                                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 != "")
                                {
                                    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 != "")
                                {
                                    who = Player.Find(p.possess);
                                    if (who == null || who.level != p.level)
                                    {
                                        p.possess = "";
                                    }
                                }

                                x = (ushort)(p.pos[0] / 32);
                                y = (ushort)(p.pos[1] / 32);
                                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();
                try
                {
                    using (WebClient web = new WebClient())
                        IP = web.DownloadString("http://dynupdate.no-ip.com/ip.php");
                }
                catch { }
#if DEBUG
                UseTextures = true;
#endif
                Log("Finished setting up server");
                ServerSetupFinished = true;
            });
        }