Beispiel #1
0
        /// <summary>
        /// Dumps information and optionally exits afterwards
        /// </summary>
        /// <param name="exit"></param>
        public void Dump(bool exit = true)
        {
            PrepareLangForDump();
            // Lang.setLang(true);
            ConfigFile.DumpDescriptions();
            Permissions.DumpDescriptions();
            ServerSideCharacters.ServerSideConfig.DumpDescriptions();
            RestManager.DumpDescriptions();
            DumpBuffs("BuffList.txt");
            DumpItems("Items-1_0.txt", 1, 235);
            DumpItems("Items-1_1.txt", 235, 604);
            DumpItems("Items-1_2.txt", 604, 2749);
            DumpItems("Items-1_3.txt", 2749, Main.maxItemTypes);
            DumpNPCs("NPCs.txt");
            DumpProjectiles("Projectiles.txt");
            DumpPrefixes("Prefixes.txt");

            if (exit)
            {
                Environment.Exit(1);
            }
        }
Beispiel #2
0
        public static void DumpDescriptions()
        {
            var sb = new StringBuilder();
            var rest = new RestManager(null);

            foreach (var method in rest.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static).OrderBy(f => f.Name))
            {
                if (method.IsStatic)
                    continue;

                var name = method.Name;

                var descattr =
                    method.GetCustomAttributes(false).FirstOrDefault(o => o is DescriptionAttribute) as DescriptionAttribute;
                var routeattr =
                    method.GetCustomAttributes(false).FirstOrDefault(o => o is RouteAttribute) as RouteAttribute;

                if (descattr != null && !string.IsNullOrWhiteSpace(descattr.Description) && routeattr != null && !string.IsNullOrWhiteSpace(routeattr.Route))
                {
                    sb.AppendLine("{0}  ".SFormat(name));
                    sb.AppendLine("Description: {0}  ".SFormat(descattr.Description));

                    var permission = method.GetCustomAttributes(false).Where(o => o is Permission);
                    if (permission.Count() > 0)
                    {
                        sb.AppendLine("Permissions: {0}".SFormat(String.Join(", ", permission.Select(p => ((Permission)p).Name))));
                    }
                    else
                    {
                        sb.AppendLine("No special permissions are required for this route.");
                    }

                    var verbs = method.GetCustomAttributes(false).Where(o => o is Verb);
                    if (verbs.Count() > 0)
                    {
                        sb.AppendLine("Verbs:");
                        foreach (Verb verb in verbs)
                        {
                            sb.AppendLine("\t{0}({1}) [{2}] - {3}".SFormat(verb.Name, verb.Required ? "Required" : "Optional", verb.ArgumentType.Name, verb.Description));
                        }
                    }

                    var nouns = method.GetCustomAttributes(false).Where(o => o is Noun);
                    if (nouns.Count() > 0)
                    {
                        sb.AppendLine("Nouns:");
                        foreach (Noun noun in nouns)
                        {
                            sb.AppendLine("\t{0}({1}) [{2}] - {3}".SFormat(noun.Name, noun.Required ? "Required" : "Optional", noun.ArgumentType.Name, noun.Description));
                        }
                    }
                    sb.AppendLine("Example Usage: {0}?{1}".SFormat(routeattr.Route,
                        string.Join("&", nouns.Select(n => String.Format("{0}={0}", ((Noun) n).Name)))));
                    sb.AppendLine();
                }
            }

            File.WriteAllText("RestDescriptions.txt", sb.ToString());
        }
Beispiel #3
0
        public override void Initialize()
        {
            HandleCommandLine(Environment.GetCommandLineArgs());

            if (!Directory.Exists(SavePath))
                Directory.CreateDirectory(SavePath);

            DateTime now = DateTime.Now;
            string logFilename;
            try
            {
                logFilename = Path.Combine(SavePath, now.ToString(LogFormat)+".log");
            }
            catch(Exception)
            {
                // Problem with the log format use the default
                logFilename = Path.Combine(SavePath, now.ToString(LogFormatDefault) + ".log");
            }
            #if DEBUG
            Log.Initialize(logFilename, LogLevel.All, false);
            #else
            Log.Initialize(logFilename, LogLevel.All & ~LogLevel.Debug, LogClear);
            #endif
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
                {
                    Log.ConsoleInfo(
                        "TShock was improperly shut down. Please use the exit command in the future to prevent this.");
                    File.Delete(Path.Combine(SavePath, "tshock.pid"));
                }
                File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture));

                ConfigFile.ConfigRead += OnConfigRead;
                FileTools.SetupConfig();

                HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs());

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "tshock.sqlite");
                    DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        var hostport = Config.MySqlHost.Split(':');
                        DB = new MySqlConnection();
                        DB.ConnectionString =
                            String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                          hostport[0],
                                          hostport.Length > 1 ? hostport[1] : "3306",
                                          Config.MySqlDbName,
                                          Config.MySqlUsername,
                                          Config.MySqlPassword
                                );
                    }
                    catch (MySqlException ex)
                    {
                        Log.Error(ex.ToString());
                        throw new Exception("MySql not setup correctly");
                    }
                }
                else
                {
                    throw new Exception("Invalid storage type");
                }

                Backups = new BackupManager(Path.Combine(SavePath, "backups"));
                Backups.KeepFor = Config.BackupKeepFor;
                Backups.Interval = Config.BackupInterval;
                Bans = new BanManager(DB);
                Warps = new WarpManager(DB);
                Users = new UserManager(DB);
                Groups = new GroupManager(DB);
                Regions = new RegionManager(DB);
                Itembans = new ItemManager(DB);
                RememberedPos = new RemeberedPosManager(DB);
                InventoryDB = new InventoryManager(DB);
                RestApi = new SecureRest(Netplay.serverListenIP, Config.RestApiPort);
                RestApi.Verify += RestApi_Verify;
                RestApi.Port = Config.RestApiPort;
                RestManager = new RestManager(RestApi);
                RestManager.RegisterRestfulCommands();

                var geoippath = Path.Combine(SavePath, "GeoIP.dat");
                if (Config.EnableGeoIP && File.Exists(geoippath))
                    Geo = new GeoIPCountry(geoippath);

                Log.ConsoleInfo(string.Format("TerrariaShock Version {0} ({1}) now running.", Version, VersionCodename));

                GameHooks.PostInitialize += OnPostInit;
                GameHooks.Update += OnUpdate;
                ServerHooks.Connect += OnConnect;
                ServerHooks.Join += OnJoin;
                ServerHooks.Leave += OnLeave;
                ServerHooks.Chat += OnChat;
                ServerHooks.Command += ServerHooks_OnCommand;
                NetHooks.GetData += OnGetData;
                NetHooks.SendData += NetHooks_SendData;
                NetHooks.GreetPlayer += OnGreetPlayer;
                NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc;
                NpcHooks.SetDefaultsInt += OnNpcSetDefaults;
                ProjectileHooks.SetDefaults += OnProjectileSetDefaults;
                WorldHooks.StartHardMode += OnStartHardMode;
                WorldHooks.SaveWorld += SaveManager.Instance.OnSaveWorld;

                GetDataHandlers.InitGetDataHandler();
                Commands.InitCommands();
                //RconHandler.StartThread();

                if (Config.RestApiEnabled)
                    RestApi.Start();

                if (Config.BufferPackets)
                    PacketBuffer = new PacketBufferer();

                Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled"));
                Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled"));

                if (Initialized != null)
                    Initialized();
            }
            catch (Exception ex)
            {
                Log.Error("Fatal Startup Exception");
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }
Beispiel #4
0
        public override void Initialize()
        {
            string logFilename;
            string logPathSetupWarning;

            try
            {
                HandleCommandLine(Environment.GetCommandLineArgs());

                if (!Directory.Exists(SavePath))
                    Directory.CreateDirectory(SavePath);

                ConfigFile.ConfigRead += OnConfigRead;
                FileTools.SetupConfig();

                Main.ServerSideCharacter = ServerSideCharacterConfig.Enabled;

                DateTime now = DateTime.Now;
                // Log path was not already set by the command line parameter?
                if (LogPath == LogPathDefault)
                    LogPath = Config.LogPath;
                try
                {
                    logFilename = Path.Combine(LogPath, now.ToString(LogFormat) + ".log");
                    if (!Directory.Exists(LogPath))
                        Directory.CreateDirectory(LogPath);
                }
                catch (Exception ex)
                {
                    logPathSetupWarning =
                        "Could not apply the given log path / log format, defaults will be used. Exception details:\n" + ex;

                    ServerApi.LogWriter.PluginWriteLine(this, logPathSetupWarning, TraceLevel.Error);

                    // Problem with the log path or format use the default
                    logFilename = Path.Combine(LogPathDefault, now.ToString(LogFormatDefault) + ".log");
                }

                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }
            catch (Exception ex)
            {
                // Will be handled by the server api and written to its crashlog.txt.
                throw new Exception("Fatal TShock initialization exception. See inner exception for details.", ex);
            }

            // Further exceptions are written to TShock's log from now on.
            try
            {
                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "tshock.sqlite");
                    DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        var hostport = Config.MySqlHost.Split(':');
                        DB = new MySqlConnection();
                        DB.ConnectionString =
                            String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                hostport[0],
                                hostport.Length > 1 ? hostport[1] : "3306",
                                Config.MySqlDbName,
                                Config.MySqlUsername,
                                Config.MySqlPassword
                                );
                    }
                    catch (MySqlException ex)
                    {
                        ServerApi.LogWriter.PluginWriteLine(this, ex.ToString(), TraceLevel.Error);
                        throw new Exception("MySql not setup correctly");
                    }
                }
                else
                {
                    throw new Exception("Invalid storage type");
                }

                if (Config.UseSqlLogs)
                    Log = new SqlLog(DB, logFilename, LogClear);
                else
                    Log = new TextLog(logFilename, LogClear);

                if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
                {
                    Log.ConsoleInfo(
                        "TShock was improperly shut down. Please use the exit command in the future to prevent this.");
                    File.Delete(Path.Combine(SavePath, "tshock.pid"));
                }
                File.WriteAllText(Path.Combine(SavePath, "tshock.pid"),
                    Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture));

                HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs());

                Backups = new BackupManager(Path.Combine(SavePath, "backups"));
                Backups.KeepFor = Config.BackupKeepFor;
                Backups.Interval = Config.BackupInterval;
                Bans = new BanManager(DB);
                Warps = new WarpManager(DB);
                Regions = new RegionManager(DB);
                Users = new UserManager(DB);
                Groups = new GroupManager(DB);
                Itembans = new ItemManager(DB);
                ProjectileBans = new ProjectileManagager(DB);
                TileBans = new TileManager(DB);
                RememberedPos = new RememberedPosManager(DB);
                CharacterDB = new CharacterManager(DB);
                RestApi = new SecureRest(Netplay.ServerIP, Config.RestApiPort);
                RestManager = new RestManager(RestApi);
                RestManager.RegisterRestfulCommands();

                var geoippath = Path.Combine(SavePath, "GeoIP.dat");
                if (Config.EnableGeoIP && File.Exists(geoippath))
                    Geo = new GeoIPCountry(geoippath);

                Log.ConsoleInfo("TShock {0} ({1}) now running.", Version, VersionCodename);

                ServerApi.Hooks.GamePostInitialize.Register(this, OnPostInit);
                ServerApi.Hooks.GameUpdate.Register(this, OnUpdate);
                ServerApi.Hooks.GameHardmodeTileUpdate.Register(this, OnHardUpdate);
                ServerApi.Hooks.GameStatueSpawn.Register(this, OnStatueSpawn);
                ServerApi.Hooks.ServerConnect.Register(this, OnConnect);
                ServerApi.Hooks.ServerJoin.Register(this, OnJoin);
                ServerApi.Hooks.ServerLeave.Register(this, OnLeave);
                ServerApi.Hooks.ServerChat.Register(this, OnChat);
                ServerApi.Hooks.ServerCommand.Register(this, ServerHooks_OnCommand);
                ServerApi.Hooks.NetGetData.Register(this, OnGetData);
                ServerApi.Hooks.NetSendData.Register(this, NetHooks_SendData);
                ServerApi.Hooks.NetGreetPlayer.Register(this, OnGreetPlayer);
                ServerApi.Hooks.NpcStrike.Register(this, NpcHooks_OnStrikeNpc);
                ServerApi.Hooks.ProjectileSetDefaults.Register(this, OnProjectileSetDefaults);
                ServerApi.Hooks.WorldStartHardMode.Register(this, OnStartHardMode);
                ServerApi.Hooks.WorldSave.Register(this, SaveManager.Instance.OnSaveWorld);
                ServerApi.Hooks.WorldChristmasCheck.Register(this, OnXmasCheck);
                ServerApi.Hooks.WorldHalloweenCheck.Register(this, OnHalloweenCheck);
                ServerApi.Hooks.NetNameCollision.Register(this, NetHooks_NameCollision);
                Hooks.PlayerHooks.PlayerPreLogin += OnPlayerPreLogin;
                Hooks.PlayerHooks.PlayerPostLogin += OnPlayerLogin;
                Hooks.AccountHooks.AccountDelete += OnAccountDelete;
                Hooks.AccountHooks.AccountCreate += OnAccountCreate;

                GetDataHandlers.InitGetDataHandler();
                Commands.InitCommands();

                if (Config.RestApiEnabled)
                    RestApi.Start();

                if (Config.BufferPackets)
                    PacketBuffer = new PacketBufferer(this);

                Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled"));
                Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled"));

                if (Initialized != null)
                    Initialized();

                Log.ConsoleInfo("Welcome to TShock for Terraria. Initialization complete.");
            }
            catch (Exception ex)
            {
                Log.Error("Fatal Startup Exception");
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }
Beispiel #5
0
        public override void Initialize()
        {
            HandleCommandLine(Environment.GetCommandLineArgs());

            if (!Directory.Exists(SavePath))
                Directory.CreateDirectory(SavePath);

            #if DEBUG
            Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All, false);
            #else
            Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All & ~LogLevel.Debug, false);
            #endif
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            try
            {
                if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
                {
                    Log.ConsoleInfo(
                        "TShock was improperly shut down. Please avoid this in the future, world corruption may result from this.");
                    File.Delete(Path.Combine(SavePath, "tshock.pid"));
                }
                File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture));

                ConfigFile.ConfigRead += OnConfigRead;
                FileTools.SetupConfig();

                HandleCommandLine_Port(Environment.GetCommandLineArgs());

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "tshock.sqlite");
                    DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        var hostport = Config.MySqlHost.Split(':');
                        DB = new MySqlConnection();
                        DB.ConnectionString =
                            String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                          hostport[0],
                                          hostport.Length > 1 ? hostport[1] : "3306",
                                          Config.MySqlDbName,
                                          Config.MySqlUsername,
                                          Config.MySqlPassword
                                );
                    }
                    catch (MySqlException ex)
                    {
                        Log.Error(ex.ToString());
                        throw new Exception("MySql not setup correctly");
                    }
                }
                else
                {
                    throw new Exception("Invalid storage type");
                }

                Backups = new BackupManager(Path.Combine(SavePath, "backups"));
                Backups.KeepFor = Config.BackupKeepFor;
                Backups.Interval = Config.BackupInterval;
                Bans = new BanManager(DB);
                Warps = new WarpManager(DB);
                Users = new UserManager(DB);
                Groups = new GroupManager(DB);
                Groups.LoadPermisions();
                Regions = new RegionManager(DB);
                Itembans = new ItemManager(DB);
                RememberedPos = new RemeberedPosManager(DB);
                Inventory = new InventoryManager(DB);
                HomeManager = new HomeManager(DB);
                ArmorShopManager = new ArmorShopManager(DB);
                WeaponShopManager = new WeaponShopManager(DB);
                ItemShopManager = new ItemShopManager(DB);
                BlockShopManager = new BlockShopManager(DB);
                OtherShopManager = new OtherShopManager(DB);
                Towns = new TownManager(DB);
                Chat = new ChatManager(DB);
                Restart = new RestartManager();
                RestApi = new SecureRest(Netplay.serverListenIP, 8080);
                RestApi.Verify += RestApi_Verify;
                RestApi.Port = Config.RestApiPort;
                RestManager = new RestManager(RestApi);
                RestManager.RegisterRestfulCommands();

                var geoippath = Path.Combine(SavePath, "GeoIP.dat");
                if (Config.EnableGeoIP && File.Exists(geoippath))
                    Geo = new GeoIPCountry(geoippath);

                    profiles = @"Z:\profiles\";
                    temp = @"Z:\profiles\temp\";

                Console.Title = string.Format("TerrariaShock Version {0} ({1})", Version, VersionCodename);
                Log.ConsoleInfo(string.Format("TerrariaShock Version {0} ({1}) now running.", Version, VersionCodename));

                GameHooks.PostInitialize += OnPostInit;
                GameHooks.Update += OnUpdate;
                ServerHooks.Connect += OnConnect;
                ServerHooks.Join += OnJoin;
                ServerHooks.Leave += OnLeave;
                ServerHooks.Chat += OnChat;
                ServerHooks.Command += ServerHooks_OnCommand;
                NetHooks.GetData += OnGetData;
                NetHooks.SendData += NetHooks_SendData;
                NetHooks.GreetPlayer += OnGreetPlayer;
                NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc;
                NpcHooks.SetDefaultsInt += OnNpcSetDefaults;
                ProjectileHooks.SetDefaults += OnProjectileSetDefaults;
                WorldHooks.StartHardMode += OnStartHardMode;
                WorldHooks.SaveWorld += OnSaveWorld;

                GetDataHandlers.InitGetDataHandler();
                Commands.InitCommands();

                if (Config.BufferPackets)
                    PacketBuffer = new PacketBufferer();

                Users.DeletePlayersAfterMinutes(TShock.Config.DeleteUserAfterMinutes, 30, false);
                Users.DeletePlayersAfterMinutes(TShock.Config.DeleteUserAfterMinutes * 2, 100, false);
                Users.DeletePlayersAfterMinutes(TShock.Config.DeleteUserAfterMinutes * 3, 10000, true);

                Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled"));
                Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled"));

                if (Initialized != null)
                    Initialized();
            }
            catch (Exception ex)
            {
                Log.Error("Fatal Startup Exception");
                Log.Error(ex.ToString());
                TShock.Backups.Backup();
                Environment.Exit(1);
            }
        }
Beispiel #6
0
        public override void Initialize()
        {
            if (!Directory.Exists(SavePath))
            {
                Directory.CreateDirectory(SavePath);
            }

#if DEBUG
            Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All, false);
#else
            Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All & ~LogLevel.Debug, false);
#endif
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;


            try
            {
                if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
                {
                    Log.ConsoleInfo("TShock was improperly shut down. Deleting invalid pid file...");
                    File.Delete(Path.Combine(SavePath, "tshock.pid"));
                }
                File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString());

                ConfigFile.ConfigRead += OnConfigRead;
                FileTools.SetupConfig();

                HandleCommandLine(Environment.GetCommandLineArgs());

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "tshock.sqlite");
                    DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        var hostport = Config.MySqlHost.Split(':');
                        DB = new MySqlConnection();
                        DB.ConnectionString =
                            String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                          hostport[0],
                                          hostport.Length > 1 ? hostport[1] : "3306",
                                          Config.MySqlDbName,
                                          Config.MySqlUsername,
                                          Config.MySqlPassword
                                          );
                    }
                    catch (MySqlException ex)
                    {
                        Log.Error(ex.ToString());
                        throw new Exception("MySql not setup correctly");
                    }
                }
                else
                {
                    throw new Exception("Invalid storage type");
                }

                Backups          = new BackupManager(Path.Combine(SavePath, "backups"));
                Backups.KeepFor  = Config.BackupKeepFor;
                Backups.Interval = Config.BackupInterval;
                Bans             = new BanManager(DB);
                Warps            = new WarpManager(DB);
                Users            = new UserManager(DB);
                Groups           = new GroupManager(DB);
                Groups.LoadPermisions();
                Regions         = new RegionManager(DB);
                Itembans        = new ItemManager(DB);
                RememberedPos   = new RemeberedPosManager(DB);
                RestApi         = new SecureRest(Netplay.serverListenIP, 8080);
                RestApi.Verify += RestApi_Verify;
                RestApi.Port    = Config.RestApiPort;
                RestManager     = new RestManager(RestApi);
                RestManager.RegisterRestfulCommands();

                var geoippath = Path.Combine(SavePath, "GeoIP.dat");
                if (Config.EnableGeoIP && File.Exists(geoippath))
                {
                    Geo = new MaxMind.GeoIPCountry(geoippath);
                }

                Log.ConsoleInfo(string.Format("TShock Version {0} ({1}) now running.", Version, VersionCodename));

                GameHooks.PostInitialize += OnPostInit;
                GameHooks.Update         += OnUpdate;
                ServerHooks.Join         += OnJoin;
                ServerHooks.Leave        += OnLeave;
                ServerHooks.Chat         += OnChat;
                ServerHooks.Command      += ServerHooks_OnCommand;
                NetHooks.GetData         += OnGetData;
                NetHooks.SendData        += NetHooks_SendData;
                NetHooks.GreetPlayer     += OnGreetPlayer;
                NpcHooks.StrikeNpc       += NpcHooks_OnStrikeNpc;

                GetDataHandlers.InitGetDataHandler();
                Commands.InitCommands();
                //RconHandler.StartThread();

                if (Config.BufferPackets)
                {
                    PacketBuffer = new PacketBufferer();
                }

                Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled"));
                Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled"));

                if (Initialized != null)
                {
                    Initialized();
                }
            }
            catch (Exception ex)
            {
                Log.Error("Fatal Startup Exception");
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }
Beispiel #7
0
        public override void Initialize()
        {
            try
            {
                HandleCommandLine(Environment.GetCommandLineArgs());

                if (Version.Major >= 4)
                    getTShockAscii();

                if (!Directory.Exists(SavePath))
                    Directory.CreateDirectory(SavePath);

                ConfigFile.ConfigRead += OnConfigRead;
                FileTools.SetupConfig();

                DateTime now = DateTime.Now;
                string logFilename;
                string logPathSetupWarning = null;
                // Log path was not already set by the command line parameter?
                if (LogPath == LogPathDefault)
                    LogPath = Config.LogPath;
                try
                {
                    logFilename = Path.Combine(LogPath, now.ToString(LogFormat)+".log");
                    if (!Directory.Exists(LogPath))
                        Directory.CreateDirectory(LogPath);
                }
                catch(Exception ex)
                {
                    logPathSetupWarning = "Could not apply the given log path / log format, defaults will be used. Exception details:\n" + ex;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(logPathSetupWarning);
                    Console.ForegroundColor = ConsoleColor.Gray;
                    // Problem with the log path or format use the default
                    logFilename = Path.Combine(LogPathDefault, now.ToString(LogFormatDefault) + ".log");
                }
            #if DEBUG
                Log.Initialize(logFilename, LogLevel.All, false);
            #else
                Log.Initialize(logFilename, LogLevel.All & ~LogLevel.Debug, LogClear);
            #endif
                if (logPathSetupWarning != null)
                    Log.Warn(logPathSetupWarning);

                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            }
            catch(Exception ex)
            {
                // Will be handled by the server api and written to its crashlog.txt.
                throw new Exception("Fatal TShock initialization exception. See inner exception for details.", ex);
            }

            // Further exceptions are written to TShock's log from now on.
            try
            {
                if (File.Exists(Path.Combine(SavePath, "tshock.pid")))
                {
                    Log.ConsoleInfo(
                        "TShock was improperly shut down. Please use the exit command in the future to prevent this.");
                    File.Delete(Path.Combine(SavePath, "tshock.pid"));
                }
                File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture));

                HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs());

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "tshock.sqlite");
                    DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        var hostport = Config.MySqlHost.Split(':');
                        DB = new MySqlConnection();
                        DB.ConnectionString =
                            String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                          hostport[0],
                                          hostport.Length > 1 ? hostport[1] : "3306",
                                          Config.MySqlDbName,
                                          Config.MySqlUsername,
                                          Config.MySqlPassword
                                );
                    }
                    catch (MySqlException ex)
                    {
                        Log.Error(ex.ToString());
                        throw new Exception("MySql not setup correctly");
                    }
                }
                else
                {
                    throw new Exception("Invalid storage type");
                }

                Backups = new BackupManager(Path.Combine(SavePath, "backups"));
                Backups.KeepFor = Config.BackupKeepFor;
                Backups.Interval = Config.BackupInterval;
                Bans = new BanManager(DB);
                Warps = new WarpManager(DB);
                Regions = new RegionManager(DB);
                Users = new UserManager(DB);
                Groups = new GroupManager(DB);
                Itembans = new ItemManager(DB);
                RememberedPos = new RememberedPosManager(DB);
                InventoryDB = new InventoryManager(DB);
                RestApi = new SecureRest(Netplay.serverListenIP, Config.RestApiPort);
                RestApi.Port = Config.RestApiPort;
                RestManager = new RestManager(RestApi);
                RestManager.RegisterRestfulCommands();

                var geoippath = Path.Combine(SavePath, "GeoIP.dat");
                if (Config.EnableGeoIP && File.Exists(geoippath))
                    Geo = new GeoIPCountry(geoippath);

                Log.ConsoleInfo(string.Format("|> Version {0} ({1}) now running.", Version, VersionCodename));

                GameHooks.PostInitialize += OnPostInit;
                GameHooks.Update += OnUpdate;
                GameHooks.HardUpdate += OnHardUpdate;
                GameHooks.StatueSpawn += OnStatueSpawn;
                ServerHooks.Connect += OnConnect;
                ServerHooks.Join += OnJoin;
                ServerHooks.Leave += OnLeave;
                ServerHooks.Chat += OnChat;
                ServerHooks.Command += ServerHooks_OnCommand;
                NetHooks.GetData += OnGetData;
                NetHooks.SendData += NetHooks_SendData;
                NetHooks.GreetPlayer += OnGreetPlayer;
                NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc;
                NpcHooks.SetDefaultsInt += OnNpcSetDefaults;
                ProjectileHooks.SetDefaults += OnProjectileSetDefaults;
                WorldHooks.StartHardMode += OnStartHardMode;
                WorldHooks.SaveWorld += SaveManager.Instance.OnSaveWorld;
                WorldHooks.ChristmasCheck += OnXmasCheck;
                NetHooks.NameCollision += NetHooks_NameCollision;
                TShockAPI.Hooks.PlayerHooks.PlayerPostLogin += OnPlayerLogin;

                GetDataHandlers.InitGetDataHandler();
                Commands.InitCommands();
                //RconHandler.StartThread();

                if (Config.RestApiEnabled)
                    RestApi.Start();

                if (Config.BufferPackets)
                    PacketBuffer = new PacketBufferer();

                Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled"));
                Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled"));

                if (Initialized != null)
                    Initialized();
            }
            catch (Exception ex)
            {
                Log.Error("Fatal Startup Exception");
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }