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 (!File.Exists("MySql.Data.dll")) { Log("MySql.Data.dll doesn't exist, Downloading"); try { using (WebClient WEB = new WebClient()) { WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/MySql.Data.dll?raw=true", "MySql.Data.dll"); } if (File.Exists("MySql.Data.dll")) { Log("MySql.Data.dll download succesful!"); } } catch { Log("Downloading MySql.Data.dll failed, please try again later"); } } if (!File.Exists("System.Data.SQLite.dll")) { Log("System.Data.SQLite.dll doesn't exist, Downloading"); try { using (WebClient WEB = new WebClient()) { WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/System.Data.SQLite.dll?raw=true", "System.Data.SQLite.dll"); } if (File.Exists("System.Data.SQLite.dll")) { Log("System.Data.SQLite.dll download succesful!"); } } catch { Log("Downloading System.Data.SQLite.dll failed, please try again later"); } } if (!File.Exists("sqlite3.dll")) { Log("sqlite3.dll doesn't exist, Downloading"); try { using (WebClient WEB = new WebClient()) { WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/sqlite3.dll?raw=true", "sqlite3.dll"); } if (File.Exists("sqlite3.dll")) { Log("sqlite3.dll download succesful!"); } } catch { Log("Downloading sqlite3.dll failed, please try again later"); } } if (!File.Exists("Newtonsoft.Json.dll")) { Log("Newtonsoft.Json.dll doesn't exist, Downloading"); try { using (WebClient WEB = new WebClient()) { WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/Newtonsoft.Json/Newtonsoft.Json.dll?raw=true", "Newtonsoft.Json.dll"); } if (File.Exists("Newtonsoft.Json.dll")) { Log("Newtonsoft.Json.dll download successful!"); } } catch { Log("Download Newtonsoft.Json.dll failed, please try again later"); } } } //UpdateGlobalSettings(); 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(); // DO NOT STICK ANYTHING IN BETWEEN HERE!!!!!!!!!!!!!!! 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:mcgalaxy.ml"); SW.WriteLine("// That would replace '$website' in any message to 'mcgalaxy.ml'"); SW.WriteLine("// It must not start with a // and it must not have a space between the 2 sides and the colon (:)"); SW.Close(); } } 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(); } // LavaSurvival constructed here... lava = new LavaSurvival(); zombie = new ZombieGame(); LoadAllSettings(); //derp if (!Server.LevelList.Contains("#(Must be comma seperated, no spaces. Must have changing levels and use level list enabled.)")) Server.LevelList.Add("#(Must be comma seperated, no spaces. Must have changing levels and use level list enabled.)"); // OmniBan omniban = new OmniBan(); timeOnline = DateTime.Now; {//MYSQL stuff try { Database.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; } Database.executeQuery(string.Format("CREATE TABLE if not exists Players (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Name TEXT, 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)" : ""))); Database.executeQuery(string.Format("CREATE TABLE if not exists Opstats (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Time DATETIME, Name TEXT, Cmd VARCHAR(40), Cmdmsg VARCHAR(40){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : ""))); if (!File.Exists("extra/alter.txt") && Server.useMySQL) { Database.executeQuery("ALTER TABLE Players MODIFY Name TEXT"); Database.executeQuery("ALTER TABLE Opstats MODIFY Name TEXT"); File.Create("extra/alter.txt"); } //since 5.5.11 we are cleaning up the table Playercmds string query = Server.useMySQL ? "SHOW TABLES LIKE 'Playercmds'" : "SELECT name FROM sqlite_master WHERE type='table' AND name='Playercmds';"; DataTable playercmds = Database.fillData(query); DataTable opstats = Database.fillData("SELECT * FROM Opstats"); //if Playercmds exists copy-filter to Ostats and remove Playercmds if (playercmds.Rows.Count != 0) { foreach (string cmd in Server.Opstats) Database.executeQuery(string.Format("INSERT INTO Opstats (Time, Name, Cmd, Cmdmsg) SELECT Time, Name, Cmd, Cmdmsg FROM Playercmds WHERE cmd = '{0}';", cmd)); Database.executeQuery("INSERT INTO Opstats (Time, Name, Cmd, Cmdmsg) SELECT Time, Name, Cmd, Cmdmsg FROM Playercmds WHERE cmd = 'review' AND cmdmsg = 'next';"); Database.fillData("DROP TABLE Playercmds"); } playercmds.Dispose(); opstats.Dispose(); // Here, since SQLite is a NEW thing from 5.3.0.0, we do not have to check for existing tables in SQLite. if (useMySQL) { // 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"); //else SQLite.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"); // else SQLite.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(); } } Economy.LoadDatabase(); UpdateStaffList(); if (levels != null) foreach (Level l in levels) { l.Unload(); } ml.Queue(delegate { try { levels = new List<Level>(maps); MapGen = new RealisticMapGen(); 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(); Level.CreateLeveldb(level); } } //Wom Textures if (UseTextures) { mainLevel.textures.sendwomid = true; mainLevel.textures.enabled = true; mainLevel.textures.MOTD = motd; mainLevel.textures.CreateCFG(); } } else { Log("mainlevel not found"); mainLevel = new Level(level, 128, 64, 128, "flat") { permissionvisit = LevelPermission.Guest, permissionbuild = LevelPermission.Guest }; mainLevel.Save(); Level.CreateLeveldb(level); } addLevel(mainLevel); // fenderrock - Make sure the level does have a physics thread if (mainLevel.physThread == null) mainLevel.StartPhysics(); } catch (Exception e) { ErrorLog(e); } }); Plugin.Load(); ml.Queue(delegate { bannedIP = PlayerList.Load("banned-ip.txt", null); ircControllers = PlayerList.Load("IRC_Controllers.txt", null); muted = PlayerList.Load("muted.txt", null); foreach (Group grp in Group.GroupList) grp.playerList = PlayerList.Load(grp.fileName, grp); if (useWhitelist) whiteList = PlayerList.Load("whitelist.txt", null); if (!File.Exists("ranks/jailed.txt")) { File.Create("ranks/jailed.txt").Close(); Server.s.Log("CREATED NEW: ranks/jailed.txt"); } Extensions.UncapitalizeAll("ranks/banned.txt"); Extensions.UncapitalizeAll("ranks/muted.txt"); }); ml.Queue(delegate { 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/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 { updateTimer.Elapsed += delegate { Player.GlobalUpdate(); PlayerBot.GlobalUpdatePosition(); }; updateTimer.Start(); }); // Heartbeat code here: ml.Queue(delegate { try { Heart.Init(); } catch (Exception e) { Server.ErrorLog(e); } }); ml.Queue(delegate { messageTimer.Elapsed += delegate { RandomMessage(); }; messageTimer.Start(); 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(); try { APIServer = new WebServer(SendResponse, "http://localhost:8080/api/"); APIServer.Run(); InfoServer = new WebServer(WhoIsResponse, "http://localhost:8080/whois/"); InfoServer.Run(); } catch { Server.s.Log("Failed to start local API server"); } IRC = new ForgeBot(Server.ircChannel, Server.ircOpChannel, Server.ircNick, Server.ircServer); GlobalChat = new GlobalChatBot(GlobalChatNick()); if (Server.irc) IRC.Connect(); if (Server.UseGlobalChat) GlobalChat.Connect(); // OmniBan stuff! new Thread(new ThreadStart(() => omniban.Load(true))).Start(); omnibanCheckTimer.Elapsed += delegate { omniban.Load(true); omniban.KickAll(); }; omnibanCheckTimer.Start(); new AutoSaver(Server.backupInterval); blockThread = new Thread(new ThreadStart(delegate { while (true) { Thread.Sleep(blockInterval * 1000); try { levels.ForEach( delegate(Level l) { try { l.saveChanges(); } catch (Exception e) { Server.ErrorLog(e); } }); } catch (Exception e) { // an exception is raised on Mono if level list is modified // while enumerating over it with ForEach Server.ErrorLog(e); } } })); blockThread.Name = "MCG_BlockUpdates"; 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.Name = "MCG_LocationCheck"; locationChecker.Start(); #if DEBUG UseTextures = true; #endif Log("Finished setting up server"); ServerSetupFinished = true; Checktimer.StartTimer(); Commands.CommandKeywords.SetKeyWords(); try { if (Server.lava.startOnStartup) Server.lava.Start(); if (Server.startZombieModeOnStartup) Server.zombie.StartGame(1, 0); //This doesnt use the main map if (Server.UseCTF) ctf = new Auto_CTF(); } catch (Exception e) { Server.ErrorLog(e); } BlockQueue.Start(); }); }
public void SendToSpawn(Level mainlevel, Auto_CTF game, Player p1) { Random rand = new Random(); if (spawnx == 0 && spawny == 0 && spawnz == 0) { ushort xx = (ushort)(rand.Next(0, mainlevel.Width)); ushort yy = (ushort)(rand.Next(0, mainlevel.Height)); ushort zz = (ushort)(rand.Next(0, mainlevel.Length)); while (mainlevel.GetTile(xx, yy, zz) != Block.air && game.OnSide((ushort)(zz * 32), this)) { xx = (ushort)(rand.Next(0, mainlevel.Width)); yy = (ushort)(rand.Next(0, mainlevel.Height)); zz = (ushort)(rand.Next(0, mainlevel.Length)); } unchecked { p1.SendPos((byte)-1, (ushort)(xx * 32), (ushort)(yy * 32), (ushort)(zz * 32), p1.rot[0], p1.rot[1]); } } else unchecked { p1.SendPos((byte)-1, spawnx, spawny, spawnz, p1.rot[0], p1.rot[1]); } }