public static RestObject Staff(RestRequestArgs args) { GroupManager groupmanager = new GroupManager(TShock.DB); UserManager usermanager = new UserManager(TShock.DB); List<string> groups = groupmanager.groups.FindAll(g => g.HasPermission("tshock.admin.kick")).Select(g => g.Name).ToList(); List<User> users = usermanager.GetUsers().Where(u => groups.Contains(u.Group)).ToList(); Dictionary<string, List<string>> RestGroups = new Dictionary<string, List<string>>(); for (int i = 0; i < groups.Count; i++) RestGroups[groups[i]] = users.Where(u => u.Group == groups[i]).Select(u => u.Name).ToList(); return new RestObject() { { "StaffList", RestGroups }, }; }
private void Check(CommandArgs args) { if (args.Parameters.Count < 1) { args.Player.SendErrorMessage("Invalid syntax! proper syntax: /lo <username>"); return; } string name = string.Join(" ", args.Parameters); TShockAPI.DB.User DbUser = new UserManager(TShock.DB).GetUserByName(name); if (DbUser == null) { args.Player.SendErrorMessage("Player not found! (Doesn't exist? Also Case Sensitivity is important)"); return; } bool online = IsOnline(DbUser.Name); TimeSpan t = DateTime.UtcNow.Subtract(DateTime.Parse(DbUser.LastAccessed)); string msg = online ? "has been online for": "was last seen online"; args.Player.SendInfoMessage($"{DbUser.Name} {msg} {GetTimeFormat(t)}{(online ? "" : " ago") }."); }
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); } }
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); } }
public static void House(CommandArgs args) { string AdminHouse = "house.admin"; // Seems right to keep the actual permission names in one place, for easy editing string UseHouse = "house.use"; string LockHouse = "house.lock"; string TeleportHouse = "house.tp"; string cmd = "help"; var ply = args.Player; // Makes the code shorter if (args.Parameters.Count > 0) cmd = args.Parameters[0].ToLower(); var player = HTools.GetPlayerByID(args.Player.Index); switch (cmd) { #region Set case "set": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if (!ply.IsLoggedIn || ply.User.ID == 0) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } int choice = 0; if (args.Parameters.Count == 2 && int.TryParse(args.Parameters[1], out choice) && choice >= 1 && choice <= 2) { if (choice == 1) ply.SendMessage("Now hit the TOP-LEFT block of the area to be protected.", Color.Yellow); if (choice == 2) ply.SendMessage("Now hit the BOTTOM-RIGHT block of the area to be protected.", Color.Yellow); ply.AwaitingTempPoint = choice; } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house set [1/2]"); break; } #endregion #region Define case "define": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if (!ply.IsLoggedIn || ply.User.ID == 0) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 1) { List<int> userOwnedHouses = new List<int>(); var maxHouses = HTools.MaxCount(ply); for (int i = 0; i < HousingDistricts.Houses.Count; i++) { var house = HousingDistricts.Houses[i]; if (HTools.OwnsHouse(ply.User.ID.ToString(), house)) userOwnedHouses.Add(house.ID); } if (userOwnedHouses.Count < maxHouses || ply.Group.HasPermission("house.bypasscount")) { if (!ply.TempPoints.Any(p => p == Point.Zero)) { string houseName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)); if (String.IsNullOrEmpty(houseName)) { ply.SendErrorMessage("House name cannot be empty."); return; } var x = Math.Min(ply.TempPoints[0].X, ply.TempPoints[1].X); var y = Math.Min(ply.TempPoints[0].Y, ply.TempPoints[1].Y); var width = Math.Abs(ply.TempPoints[0].X - ply.TempPoints[1].X) + 1; var height = Math.Abs(ply.TempPoints[0].Y - ply.TempPoints[1].Y) + 1; var maxSize = HTools.MaxSize(ply); if (((width * height) <= maxSize && width >= HousingDistricts.HConfig.MinHouseWidth && height >= HousingDistricts.HConfig.MinHouseHeight) || ply.Group.HasPermission("house.bypasssize")) { Rectangle newHouseR = new Rectangle(x, y, width, height); for (int i = 0; i < HousingDistricts.Houses.Count; i++) { var house = HousingDistricts.Houses[i]; if (!HouseTools.WorldMismatch(house) && (newHouseR.Intersects(house.HouseArea) && !userOwnedHouses.Contains(house.ID)) && !HousingDistricts.HConfig.OverlapHouses) { ply.SendErrorMessage("Your selected area overlaps another players' house, which is not allowed."); return; } } if (newHouseR.Intersects(new Rectangle(Main.spawnTileX, Main.spawnTileY, 1, 1))) { ply.SendErrorMessage("Your selected area overlaps spawnpoint, which is not allowed."); return; } for (int i = 0; i < TShock.Regions.Regions.Count; i++) { var Region = TShock.Regions.Regions[i]; if (newHouseR.Intersects(Region.Area) && !Region.HasPermissionToBuildInRegion(ply)) { ply.SendErrorMessage(string.Format("Your selected area overlaps region '{0}', which is not allowed.", Region.Name)); return; } } if (HouseTools.AddHouse(x, y, width, height, houseName, ply.User.ID.ToString(), 0, 0)) { ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; ply.SendMessage("You have created new house " + houseName, Color.Yellow); HouseTools.AddNewUser(houseName, ply.User.ID.ToString()); TShock.Log.ConsoleInfo("{0} has created a new house: \"{1}\".", ply.User.Name, houseName); } else { var WM = HouseTools.WorldMismatch(HouseTools.GetHouseByName(houseName)) ? " with a different WorldID!" : ""; ply.SendErrorMessage("House " + houseName + " already exists" + WM); } } else { if ((width * height) >= maxSize) { ply.SendErrorMessage("Your house exceeds the maximum size of " + maxSize.ToString() + " blocks."); ply.SendErrorMessage("Width: " + width.ToString() + ", Height: " + height.ToString() + ". Points have been cleared."); ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; } else if (width < HousingDistricts.HConfig.MinHouseWidth) { ply.SendErrorMessage("Your house width is smaller than server minimum of " + HousingDistricts.HConfig.MinHouseWidth.ToString() + " blocks."); ply.SendErrorMessage("Width: " + width.ToString() + ", Height: " + height.ToString() + ". Points have been cleared."); ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; } else { ply.SendErrorMessage("Your house height is smaller than server minimum of " + HousingDistricts.HConfig.MinHouseHeight.ToString() + " blocks."); ply.SendErrorMessage("Width: " + width.ToString() + ", Height: " + height.ToString() + ". Points have been cleared."); ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; } } } else ply.SendErrorMessage("Points not set up yet"); } else ply.SendErrorMessage("House define failed: You have too many houses!"); } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house define [name]"); break; } #endregion #region Redefine case "redefine": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if (!ply.IsLoggedIn || ply.User.ID == 0) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 1) { if (!ply.TempPoints.Any(p => p == Point.Zero)) { string houseName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)); if (HTools.OwnsHouse(ply.User, houseName) || ply.Group.HasPermission(AdminHouse)) { var x = Math.Min(ply.TempPoints[0].X, ply.TempPoints[1].X); var y = Math.Min(ply.TempPoints[0].Y, ply.TempPoints[1].Y); var width = Math.Abs(ply.TempPoints[0].X - ply.TempPoints[1].X) + 1; var height = Math.Abs(ply.TempPoints[0].Y - ply.TempPoints[1].Y) + 1; var maxSize = HTools.MaxSize(ply); if ((width * height) <= maxSize && width >= HousingDistricts.HConfig.MinHouseWidth && height >= HousingDistricts.HConfig.MinHouseHeight) { Rectangle newHouseR = new Rectangle(x, y, width, height); for (int i = 0; i < HousingDistricts.Houses.Count; i++) { var house = HousingDistricts.Houses[i]; if (!HouseTools.WorldMismatch(house) && (newHouseR.Intersects(house.HouseArea) && !house.Owners.Contains(ply.User.ID.ToString())) && !HousingDistricts.HConfig.OverlapHouses) { ply.SendErrorMessage("Your selected area overlaps another players' house, which is not allowed."); return; } } if (newHouseR.Intersects(new Rectangle(Main.spawnTileX, Main.spawnTileY, 1, 1))) { ply.SendErrorMessage("Your selected area overlaps spawnpoint, which is not allowed."); return; } for (int i = 0; i < TShock.Regions.Regions.Count; i++) { var Region = TShock.Regions.Regions[i]; if (newHouseR.Intersects(Region.Area) && !Region.HasPermissionToBuildInRegion(ply)) { ply.SendErrorMessage(string.Format("Your selected area overlaps region '{0}', which is not allowed.", Region.Name)); return; } } if (HouseTools.RedefineHouse(x, y, width, height, houseName)) { ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; ply.SendMessage("Redefined house " + houseName, Color.Yellow); } else ply.SendErrorMessage("Error redefining house " + houseName); } else { if ((width * height) >= maxSize) { ply.SendErrorMessage("Your house exceeds the maximum size of " + maxSize.ToString() + " blocks."); ply.SendErrorMessage("Width: " + width.ToString() + ", Height: " + height.ToString() + ". Points have been cleared."); ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; } else if (width < HousingDistricts.HConfig.MinHouseWidth) { ply.SendErrorMessage("Your house width is smaller than server minimum of " + HousingDistricts.HConfig.MinHouseWidth.ToString() + " blocks."); ply.SendErrorMessage("Width: " + width.ToString() + ", Height: " + height.ToString() + ". Points have been cleared."); ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; } else { ply.SendErrorMessage("Your house height is smaller than server minimum of " + HousingDistricts.HConfig.MinHouseHeight.ToString() + " blocks."); ply.SendErrorMessage("Width: " + width.ToString() + ", Height: " + height.ToString() + ". Points have been cleared."); ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; } } } else ply.SendErrorMessage("You do not own house: " + houseName); } else ply.SendErrorMessage("Points not set up yet"); } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house redefine [name]"); break; } #endregion #region Allow case "allow": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 2) { switch (args.Parameters[1]) { case "add": { string playerName = args.Parameters[2]; User playerID; House house = null; if (args.Parameters.Count == 3) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } if (args.Parameters.Count == 4) { house = HouseTools.GetHouseByName(args.Parameters[3]); } if (house == null) { ply.SendErrorMessage("No such house!"); return; } string houseName = house.Name; if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { if ((playerID = TShock.Users.GetUserByName(playerName)) != null) { if (!HTools.OwnsHouse(playerID.ID.ToString(), house)) { if (HouseTools.AddNewUser(houseName, playerID.ID.ToString())) { ply.SendInfoMessage("Added user {0} to {1}.", playerName, houseName); } else ply.SendErrorMessage("House {0} not found.", houseName); } else ply.SendErrorMessage("Player {0} is already allowed to build in {1}.", playerName, house.Name); } else ply.SendErrorMessage("Player {0} not found.", playerName); } else ply.SendErrorMessage("You do not own house: " + houseName); break; } case "del": { string playerName = args.Parameters[2]; User playerID; House house = null; if (args.Parameters.Count == 3) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } if (args.Parameters.Count == 4) { house = HouseTools.GetHouseByName(args.Parameters[3]); } if (house == null) { ply.SendErrorMessage("No such house!"); return; } string houseName = house.Name; if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { if ((playerID = TShock.Users.GetUserByName(playerName)) != null) { if (HouseTools.DeleteUser(houseName, playerID.ID.ToString())) { ply.SendInfoMessage("Deleted user {0} from {1}.", playerName, houseName); } else ply.SendErrorMessage("House {0} not found.", houseName); } else ply.SendErrorMessage("Player {0} not found.", playerName); } else ply.SendErrorMessage("You do not own house: " + houseName); break; } } } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house allow (add/del) [name] [house]"); break; } #endregion #region Teleport case "tp": { if (!ply.Group.HasPermission(TeleportHouse)) { ply.SendErrorMessage("You do not have access to this command."); return; } if (args.Parameters.Count > 1) { var house = HouseTools.GetHouseByName(args.Parameters[1]); if (house == null) { ply.SendErrorMessage("The {0} does not exist!", args.Parameters[1]); return; } ply.Teleport(house.HouseArea.Center.X * 16, house.HouseArea.Center.Y * 16); ply.SendInfoMessage("You have been teleported to {0}.", house.Name); TShock.Log.Info("{0} teleported to a house: {1}.", ply.Name, house.Name); } break; } #endregion #region Delete case "delete": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 2) { ply.SendErrorMessage("Invalid syntax! Proper syntax: /house delete [house]"); return; } if (args.Parameters.Count > 0) { House house = null; if (args.Parameters.Count == 1) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } else if (args.Parameters.Count == 2) { string houseName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)); house = HouseTools.GetHouseByName(houseName); if (house == null) { ply.SendErrorMessage("This house doesn't exist!"); return; } } if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { try { TShock.DB.Query("DELETE FROM HousingDistrict WHERE Name=@0", house.Name); } catch (Exception ex) { TShock.Log.Error(ex.ToString()); } HousingDistricts.Houses.Remove(house); ply.SendInfoMessage("You deleted {0}.", house.Name); TShock.Log.ConsoleInfo("{0} has deleted house: {1}.", ply.User.Name, house.Name); break; } else { ply.SendErrorMessage("You are not the owner of {0}.", house.Name); break; } } break; } #endregion #region Purge House case "purge": { if (!ply.Group.HasPermission(AdminHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 2) { ply.SendErrorMessage("Invalid syntax! Proper syntax: /house purge [house]"); return; } if (args.Parameters.Count > 0) { House house = null; if (args.Parameters.Count == 1) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } if (args.Parameters.Count == 2) { house = HouseTools.GetHouseByName(args.Parameters[1]); } if (house == null) { ply.SendErrorMessage("There is no house{0}!", args.Parameters.Count == 2 ? " by that name" : " at this location"); return; } if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { int x = 0, y = 0, x2 = 0, y2 = 0, bottomx = 0, bottomy = 0; var reader = TShock.DB.QueryReader("SELECT * FROM HousingDistrict WHERE Name=@0", house.Name); if (reader.Read()) { x = reader.Get<int>("TopX"); y = reader.Get<int>("TopY"); bottomx = reader.Get<int>("BottomX"); bottomy = reader.Get<int>("BottomY"); } x2 = x + bottomx - 1; y2 = y + bottomy - 1; ply.SendInfoMessage("Location: ({0}, {1}) {2}x{3}", x, y, bottomx, bottomy); for (int i = x; i <= x2; i++) { for (int j = y; j <= y2; j++) { var tile = Main.tile[i, j]; tile.wall = 0; tile.active(false); tile.frameX = -1; tile.frameY = -1; tile.liquidType(0); tile.liquid = 0; tile.type = 0; } } int lowX = Netplay.GetSectionX(x); int highX = Netplay.GetSectionX(x2); int lowY = Netplay.GetSectionY(y); int highY = Netplay.GetSectionY(y2); foreach (RemoteClient sock in Netplay.Clients.Where(s => s.IsActive)) { for (int i = lowX; i <= highX; i++) { for (int j = lowY; j <= highY; j++) sock.TileSections[i, j] = false; } } reader.Dispose(); try { TShock.DB.Query("DELETE FROM HousingDistrict WHERE Name=@0", house.Name); } catch (Exception ex) { TShock.Log.Error(ex.ToString()); } HousingDistricts.Houses.Remove(house); ply.SendInfoMessage("You deleted {0}.", house.Name); TShock.Log.Info("{0} deleted purged house: {1}", ply.Name, house.Name); break; } else { ply.SendErrorMessage("You are not the owner of {0}.", house.Name); break; } } break; } #endregion #region Purge Expired Houses case "purgeexp": { if (!ply.Group.HasPermission(AdminHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count == 2) { int count = 0; var H = HousingDistricts.Houses.Count; for (int h = 0; h < H; h++) { var house = HousingDistricts.Houses[h]; try { if(house != null && !HouseTools.WorldMismatch(house)) { var UserID = house.Owners[0]; var days = args.Parameters[1]; User User = HTools.GetUserIDHouse(UserID); TimeSpan t = DateTime.UtcNow - DateTime.UtcNow; if (User != null) { t = DateTime.UtcNow.Subtract(DateTime.Parse(User.LastAccessed)); } if (User == null || t.Days >= Convert.ToInt32(days)) { if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { int x = 0, y = 0, x2 = 0, y2 = 0, bottomx = 0, bottomy = 0; var reader = TShock.DB.QueryReader("SELECT * FROM HousingDistrict WHERE Name=@0", house.Name); if (reader.Read()) { x = reader.Get<int>("TopX"); y = reader.Get<int>("TopY"); bottomx = reader.Get<int>("BottomX"); bottomy = reader.Get<int>("BottomY"); ply.SendInfoMessage("Location: {0}, {1} ({2}x{3}).", x, y, bottomx, bottomy); } x2 = x + bottomx - 1; y2 = y + bottomy - 1; for (int i = x; i <= x2; i++) { for (int j = y; j <= y2; j++) { var tile = Main.tile[i, j]; tile.wall = 0; tile.active(false); tile.frameX = -1; tile.frameY = -1; tile.liquidType(0); tile.liquid = 0; tile.type = 0; tile.wire(false); tile.wire2(false); tile.wire3(false); tile.wire4(false); } } int lowX = Netplay.GetSectionX(x); int highX = Netplay.GetSectionX(x2); int lowY = Netplay.GetSectionY(y); int highY = Netplay.GetSectionY(y2); foreach (RemoteClient sock in Netplay.Clients.Where(s => s.IsActive)) { for (int i = lowX; i <= highX; i++) { for (int j = lowY; j <= highY; j++) sock.TileSections[i, j] = false; } } reader.Dispose(); try { TShock.DB.Query("DELETE FROM HousingDistrict WHERE Name=@0", house.Name); } catch (Exception ex) { TShock.Log.Error(ex.ToString()); } HousingDistricts.Houses.Remove(house); ply.SendInfoMessage("House: {0} deleted by {1}.", house.Name, args.Player.User.Name); TShock.Log.Info("{0} deleted {1} House.", ply.Name, house.Name); H--; h--; count++; } else { ply.SendErrorMessage("You do not own house: " + house.Name); break; } } } } catch (Exception ex) { TShock.Log.Error(ex.ToString()); continue; } } ply.SendMessage(string.Format("{0} deleted {1} house(s).", ply.Name, count), Color.LawnGreen); TShock.Log.Info("{0} deleted {1} house(s).", ply.Name, count); } else if (args.Parameters.Count > 3) { ply.SendErrorMessage("Invalid syntax! Proper syntax: /house purgeexp <days>"); } break; } #endregion #region Clear case "clear": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } ply.TempPoints[0] = Point.Zero; ply.TempPoints[1] = Point.Zero; ply.AwaitingTempPoint = 0; ply.SendMessage("Cleared points!", Color.Yellow); break; } #endregion #region Search case "search": { if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer || !ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if (args.Parameters.Count > 2) { ply.SendErrorMessage("Invalid syntax! Proper syntax: /house search <player>"); return; } if (args.Parameters.Count == 2) { List<string> HousesBelonged = new List<string>(); User user = TShock.Users.GetUserByName(args.Parameters[1]); if (user != null) { House house = null; var H = HousingDistricts.Houses.Count; for (int h = 0; h < H; h++) { house = HousingDistricts.Houses[h]; if (house != null) { for (int i = 0; i < house.Owners.Count; i++) { User owner = HTools.GetUserIDHouse(house.Owners[i]); if (owner != null && user.Name == owner.Name && !HousesBelonged.Contains(house.Name)) HousesBelonged.Add(house.Name); } for (int i = 0; i < house.Visitors.Count; i++) { User visitor = HTools.GetUserIDHouse(house.Visitors[i]); if (visitor != null && user.Name == visitor.Name && !HousesBelonged.Contains(house.Name)) HousesBelonged.Add(house.Name); } } } ply.SendMessage(string.Format("Houses found with {0}: {1}", user.Name, string.Join(", ", HousesBelonged)), Color.LawnGreen); TShock.Log.Info("{0} used House Search: {1}", args.Parameters[1]); } else ply.SendErrorMessage("User by that name does not exist!"); } break; } #endregion #region List case "list": { //How many regions per page const int pagelimit = 15; //How many regions per line const int perline = 5; //Pages start at 0 but are displayed and parsed at 1 int page = 0; if (args.Parameters.Count > 1) { if (!int.TryParse(args.Parameters[1], out page) || page < 1) { ply.SendErrorMessage(string.Format("Invalid page number ({0})", page)); return; } page--; //Substract 1 as pages are parsed starting at 1 and not 0 } List<House> houses = new List<House>(); for (int i = 0; i < HousingDistricts.Houses.Count; i++) { var house = HousingDistricts.Houses[i]; if (!HouseTools.WorldMismatch(house)) houses.Add(house); } // Are there even any houses to display? if (houses.Count == 0) { ply.SendMessage("There are currently no houses defined.", Color.Yellow); return; } int pagecount = houses.Count / pagelimit; if (page > pagecount) { ply.SendErrorMessage(string.Format("Page number exceeds pages ({0}/{1})", page + 1, pagecount + 1)); return; } ply.SendMessage(string.Format("Current Houses ({0}/{1}):", page + 1, pagecount + 1), Color.Green); //Add up to pagelimit names to a list var nameslist = new List<string>(); for (int i = (page * pagelimit); (i < ((page * pagelimit) + pagelimit)) && i < houses.Count; i++) nameslist.Add(houses[i].Name); //convert the list to an array for joining var names = nameslist.ToArray(); for (int i = 0; i < names.Length; i += perline) ply.SendMessage(string.Join(", ", names, i, Math.Min(names.Length - i, perline)), Color.Yellow); if (page < pagecount) ply.SendMessage(string.Format("Type /house list {0} for more houses.", (page + 2)), Color.Yellow); break; } #endregion #region Resize case "resize": { int iAmount = 0; if (args.Parameters.Count == 3 && int.TryParse(args.Parameters[2], out iAmount) && !ply.TempPoints.Any(p => p == Point.Zero)) { switch (args.Parameters[1]) { case "up": case "u": ply.TempPoints[0].Y -= iAmount; break; case "left": case "l": ply.TempPoints[0].X -= iAmount; break; case "down": case "d": ply.TempPoints[1].Y += iAmount; break; case "right": case "r": ply.TempPoints[1].X += iAmount; break; } } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house resize <u/d/l/r> <amount>"); break; } #endregion #region Info case "info": { if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer || !ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if (args.Parameters.Count > 2) { ply.SendErrorMessage("Invalid syntax! Proper syntax: /house info [house]"); return; } if (args.Parameters.Count > 0) { House house = null; if (args.Parameters.Count == 1) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } if (args.Parameters.Count == 2) { house = HouseTools.GetHouseByName(args.Parameters[1]); } if (house == null) { ply.SendErrorMessage("There is no house{0}!", args.Parameters.Count == 2 ? " by that name" : " at this location"); return; } try { List<string> OwnersName = new List<string>(); List<string> VisitorsName = new List<string>(); for (int i = 0; i < house.Owners.Count; i++) { User Owner = HTools.GetUserIDHouse(house.Owners[i]); if (Owner != null) OwnersName.Add(Owner.Name); } for (int i = 0; i < house.Visitors.Count; i++) { User Visitor = HTools.GetUserIDHouse(house.Visitors[i]); if (Visitor != null) VisitorsName.Add(Visitor.Name); } var UserID = house.Owners[0]; TShockAPI.DB.User DbUser = new UserManager(TShock.DB).GetUserByID(System.Convert.ToInt32(UserID)); TimeSpan t = DateTime.UtcNow.Subtract(DateTime.Parse(DbUser.LastAccessed)); ply.SendMessage(string.Format("{0} ({1} | {2})", house.Name, house.ChatEnabled == 1 ? "True" : "False", house.Locked == 1 ? "Private" : "Public"), Color.LawnGreen); ply.SendMessage(string.Format("Owners: {0}", string.Join(", ", OwnersName)), Color.LawnGreen); ply.SendMessage(string.Format("Visitors: {0}", string.Join(", ", VisitorsName)), Color.LawnGreen); ply.SendMessage(string.Format("Last Online: {0}D, {1}H, {2}M", t.Days, t.Hours, t.Minutes), Color.LawnGreen); TShock.Log.Info("{0} used House Info: {1}", ply.Name, house.Name); } catch (Exception ex) { TShock.Log.Error(ex.ToString()); } } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house info [house]"); break; } #endregion #region Expired House case "expired": { if (!ply.Group.HasPermission(AdminHouse)) { ply.SendErrorMessage("You do not have access to this command."); return; } if (args.Parameters.Count == 2) { int count = 0; var t = DateTime.UtcNow - DateTime.UtcNow; var days = args.Parameters[1]; var J = HousingDistricts.Houses.Count; for (int j = 0; j < J; j++) { var house = HousingDistricts.Houses[j]; try { List<string> OwnerList = new List<string>(); List<string> VisitorList = new List<string>(); var UserID = house.Owners[0]; User user = HTools.GetUserIDHouse(UserID); if (user != null) { t = DateTime.UtcNow.Subtract(DateTime.Parse(user.LastAccessed)); } if (user == null || t.Days >= Convert.ToInt32(days)) { for (int i = 0; i < house.Owners.Count; i++) { User Owner = HTools.GetUserIDHouse(house.Owners[i]); if (Owner != null) OwnerList.Add(Owner.Name); } for (int i = 0; i < house.Visitors.Count; i++) { User Visitor = HTools.GetUserIDHouse(house.Visitors[i]); if (Visitor != null) OwnerList.Add(Visitor.Name); } ply.SendMessage(string.Format("{0} ({1}D, {2}H, {3}M)", house.Name, t.Days, t.Hours, t.Minutes), Color.White); ply.SendMessage(string.Format("Owners: {0}", string.Join(", ", OwnerList)), Color.LawnGreen); ply.SendMessage(string.Format("Visitors: {0}", string.Join(", ", VisitorList)), Color.LawnGreen); TShock.Log.Info("{0} searched Expired House: {1}", ply.Name, house.Name); count++; } } catch (Exception ex) { TShock.Log.Error(ex.ToString()); continue; } } ply.SendMessage(string.Format("{0} searched {1} house(s).", ply.Name, count), Color.LawnGreen); TShock.Log.Info("{0} searched {1} house(s).", ply.Name, count); } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house expired <days>"); break; } #endregion #region Lock case "lock": { if (!ply.Group.HasPermission(LockHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (ply.Group.HasPermission("house.lock")) { if (args.Parameters.Count > 1) { string houseName = String.Join(" ", args.Parameters.GetRange(1, args.Parameters.Count - 1)); var house = HouseTools.GetHouseByName(houseName); if (house == null) { ply.SendErrorMessage("No such house!"); return; } if (HTools.OwnsHouse(ply.User.ID.ToString(), house)) { bool locked = HouseTools.ChangeLock(house); ply.SendMessage("House: " + houseName + (locked ? " locked" : " unlocked"), Color.Yellow); TShock.Log.ConsoleInfo("{0} has locked house: \"{1}\".", ply.User.Name, houseName); } else ply.SendErrorMessage("You do not own House: " + houseName); } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house lock [house]"); } else ply.SendErrorMessage("You do not have access to that command."); break; } #endregion #region Chat case "chat": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 1) { var house = HouseTools.GetHouseByName(args.Parameters[1]); if (house == null) { ply.SendErrorMessage("No such house!"); return; } if (HTools.OwnsHouse(ply.User, house.Name)) { if (args.Parameters.Count > 2) { if (args.Parameters[2].ToLower() == "on") { HouseTools.ToggleChat(house, 1); ply.SendMessage(house.Name + " chat is now enabled.", Color.Lime); } else if (args.Parameters[2].ToLower() == "off") { HouseTools.ToggleChat(house, 0); ply.SendMessage(house.Name + " chat is now disabled.", Color.Lime); } else ply.SendErrorMessage("Invalid syntax! Use /house chat <housename> (on|off)"); } else { HouseTools.ToggleChat(house, (house.ChatEnabled == 0 ? 1 : 0)); ply.SendMessage(house.Name + " chat is now " + (house.ChatEnabled == 0 ? "disabled." : "enabled."), Color.Lime); } } else ply.SendErrorMessage("You do not own " + house.Name + "."); } else ply.SendErrorMessage("Invalid syntax! Use /house chat <house> (on|off)"); break; } #endregion #region Visitor case "visitor": { if (!ply.Group.HasPermission(UseHouse)) { ply.SendErrorMessage("You do not have permission to use this command!"); return; } if ((!ply.IsLoggedIn || ply.User.ID == 0) && ply.RealPlayer) { ply.SendErrorMessage("You must log-in to use House Protection."); return; } if (args.Parameters.Count > 2) { switch (args.Parameters[1]) { case "add": { string playerName = args.Parameters[2]; User playerID; House house = null; if (args.Parameters.Count == 3) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } if (args.Parameters.Count == 4) { house = HouseTools.GetHouseByName(args.Parameters[3]); } if (house == null) { ply.SendErrorMessage("No such house!"); return; } string houseName = house.Name; if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { if ((playerID = TShock.Users.GetUserByName(playerName)) != null) { if (!HTools.CanVisitHouse(playerID.ID.ToString(), house)) { if (HouseTools.AddNewVisitor(house, playerID.ID.ToString())) ply.SendInfoMessage("Added {0} to {1} as a visitor.", playerName, houseName); else ply.SendErrorMessage("House {0} not found.", houseName); } else ply.SendErrorMessage("Player {0} is already allowed to visit {1}.", playerName, houseName); } else ply.SendErrorMessage("Player {0} not found.", playerName); } else ply.SendErrorMessage("You do not own house: {0}.", house.Name); break; } case "del": { string playerName = args.Parameters[2]; User playerID; House house = null; if (args.Parameters.Count == 3) { house = HTools.HouseAtPosition(ply.TileX, ply.TileY); } if (args.Parameters.Count == 4) { house = HouseTools.GetHouseByName(args.Parameters[3]); } if (house == null) { ply.SendErrorMessage("No such house!"); return; } string houseName = house.Name; if (HTools.OwnsHouse(ply.User, house.Name) || ply.Group.HasPermission(AdminHouse)) { if ((playerID = TShock.Users.GetUserByName(playerName)) != null) { if (HouseTools.DeleteVisitor(house, playerID.ID.ToString())) ply.SendInfoMessage("Removed user {0} from {1} as a visitor.", playerName, houseName); else ply.SendErrorMessage("House " + houseName + " not found"); } else ply.SendErrorMessage("Player " + playerName + " not found"); } else ply.SendErrorMessage("You do not own house: " + houseName); break; } } } else ply.SendErrorMessage("Invalid syntax! Proper syntax: /house visitor (add/del) [name] [house]"); break; } #endregion #region Reload Plugin case "reload": { if (ply.Group.HasPermission("house.root")) HouseReload(args); break; } #endregion case "help": default: { int pageNumber; int pageParamIndex = 0; if (args.Parameters.Count > 1) pageParamIndex = 1; if (!PaginationTools.TryParsePageNumber(args.Parameters, pageParamIndex, args.Player, out pageNumber)) return; List<int> usersOwnedHouses = new List<int>(); List<string> usersOwnedHousesName = new List<string>(); var userMaxHouses = HTools.MaxCount(args.Player); for (int i = 0; i < HousingDistricts.Houses.Count; i++) { var house = HousingDistricts.Houses[i]; if (HTools.OwnsHouse(ply.User.ID.ToString(), house)) { usersOwnedHouses.Add(house.ID); usersOwnedHousesName.Add(house.Name); } } args.Player.SendInfoMessage("You've defined {0} of {1} houses so far: {2}", usersOwnedHouses.Count, userMaxHouses, string.Join(", ", usersOwnedHousesName)); List<string> lines = new List<string> { "set <1/2> - Sets the temporary house points.", "define <name> - Defines the house with the current temporary points.", "redefine <name> - Defines the house with the given name.", "delete <name> - Deletes the given house.", "allow (add/del) <name> <house> - Add/Delete a player to the house.", "tp <house> - Teleports the player to a house.", "delete [house] - Delete a house from record.", "purge [house] - Purge a house from the world and record.", "purgeexp <days> - Purge all houses inactive for set days.", "clear - Clear the temporary house points.", "list - List all houses on record.", "resize <u/d/l/r> <amount> - Resize the selection of temporary points.", "info <house> - Get information about the house.", "expired <days> - Check for expired houses for set days.", "lock <house> - Lock the house from entry.", "chat <house> (on/off) - Enable/Disable house chat.", "visitor (add/del) <name> <house> - Add/Delete a visitor from the house.", }; if (args.Player.Group.HasPermission(TeleportHouse)) lines.Add("tp <house> - Teleports you to the given house's center."); PaginationTools.SendPage( args.Player, pageNumber, lines, new PaginationTools.Settings { HeaderFormat = "Available House Sub-Commands ({0}/{1}):", FooterFormat = "Type {0}house {{0}} for more sub-commands.".SFormat(Commands.Specifier) } ); break; } } }
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); 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 += GetData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); //RconHandler.StartThread(); if (Config.BufferPackets) bufferer = new PacketBufferer(); Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
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); } }
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); } }
private void Check(CommandArgs args) { if (args.Parameters.Count < 1) { args.Player.SendErrorMessage("Invalid syntax! proper syntax: /lo <username>"); return; } string name = string.Join(" ", args.Parameters); TShockAPI.DB.User DbUser = new UserManager(TShock.DB).GetUserByName(name); if (DbUser == null) { args.Player.SendErrorMessage("Player not found! (Doesn't exist? Also Case Sensitivity is important)"); return; } foreach (TSPlayer ts in TShock.Players) { if (ts == null) continue; if (ts.Name == DbUser.Name) { args.Player.SendErrorMessage("This player is still online!"); return; } } TimeSpan t = DateTime.UtcNow.Subtract(DateTime.Parse(DbUser.LastAccessed)); args.Player.SendInfoMessage(string.Format("{0} was last seen online {1} ago", DbUser.Name, GetTimeFormat(t))); }
private void Check(CommandArgs args) { if (args.Parameters.Count < 1) { // args.Player.SendErrorMessage("Invalid syntax! proper syntax: /lo <username>"); List<User> users = new UserManager(TShock.DB).GetUsers(); foreach (User u in users) { if (u.LastAccessed == null) continue; TimeSpan time = DateTime.UtcNow.Subtract(DateTime.Parse(u.LastAccessed)); if (isOnline(u.Name)) { args.Player.SendInfoMessage(string.Format("{0} online: for {1}", u.Name, GetTimeFormat(time))); } else { args.Player.SendInfoMessage(string.Format("{0} last seen: {1} ago", u.Name, GetTimeFormat(time))); } } return; } string name = string.Join(" ", args.Parameters); TShockAPI.DB.User DbUser = new UserManager(TShock.DB).GetUserByName(name); if (DbUser == null) { args.Player.SendErrorMessage("Player not found! (Doesn't exist? Also Case Sensitivity is important)"); return; } if (isOnline(DbUser.Name)) { args.Player.SendInfoMessage(DbUser.Name + " is still online!"); return; } TimeSpan t = DateTime.UtcNow.Subtract(DateTime.Parse(DbUser.LastAccessed)); args.Player.SendInfoMessage(string.Format("{0} -> {1} ago", DbUser.Name, GetTimeFormat(t))); }