/// <summary> /// Updates the list of ban records. /// </summary> /// <param name="banJsonString"></param> public void UpdateBanList(string banJsonString) { banlist.Clear(); dynamic obj = JsonConvert.DeserializeObject(banJsonString); foreach (dynamic br in obj) { BanRecord b = JsonToBanRecord(br); banlist.Add(b); } UpdateBans(); }
private void Kick(Entity player, BanRecord record) { LogIt(record); Log.Write(LogLevel.Info, "Player Kicked by HwId: " + player.Name + ", Hwid: " + player.HWID + ", IP: " + player.IP.Address.ToString()); UiC_Loader.Instance.AfterDelay(2000, () => { player.Kick("Banned for " + record.Reason + " By ^3UiC^7. Discord: uic.elitesnipers.pw/discord"); }); Utilities.RawSayAll($"Player ^3{player.Name} ^7kicked by ^3UiC^7, Reason: {record.Reason}"); return; }
/// <summary> /// Adds a ban manually. /// </summary> /// <param name="ban"></param> /// <returns></returns> internal static void AddBan(BanRecord ban) { string existingRecord = GetResourceKvpString(BAN_KVP_PREFIX + ban.uuid.ToString()); if (string.IsNullOrEmpty(existingRecord)) { SetResourceKvp(BAN_KVP_PREFIX + ban.uuid.ToString(), JsonConvert.SerializeObject(ban)); bansHaveChanged = true; } else { Log("Ban record already exists, this is very odd.", LogLevel.error); } }
/// <summary> /// Adds a ban manually. /// </summary> /// <param name="ban"></param> /// <returns></returns> internal static async Task <bool> AddBan(BanRecord ban) { if (useJson) { Log("Refreshing banned players list.", LogLevel.info); BannedPlayersList = await GetBanList(); bool found = false; foreach (BanRecord b in BannedPlayersList) { b.identifiers.ForEach(i => { if (ban.identifiers.Contains(i)) { found = true; } }); if (found) { BannedPlayersList.Remove(b); break; } } Log("Player is found as already banned? : " + found.ToString(), found ? LogLevel.warning : LogLevel.info); BannedPlayersList.Add(ban); var formattingMode = Formatting.None; if (BannedPlayersList.Count < 100) { formattingMode = Formatting.Indented; } var output = JsonConvert.SerializeObject(BannedPlayersList, formattingMode); while (readingOrWritingToBanFile) { await Delay(0); } readingOrWritingToBanFile = true; bool successful = SaveResourceFile(GetCurrentResourceName(), "bans.json", output, -1); readingOrWritingToBanFile = false; return(successful); } else { AddSqlBan(ban); return(true); } }
/// <summary> /// Removes a ban record from the banned players list. /// </summary> /// <param name="record"></param> /// <returns></returns> public static async Task <bool> RemoveBan(BanRecord record) { BannedPlayersList = await GetBanList(); List <int> itemsToRemove = new List <int>(); foreach (BanRecord ban in BannedPlayersList) { if (!itemsToRemove.Contains(BannedPlayersList.IndexOf(ban))) { var found = 0; foreach (string s in ban.identifiers) { if (record.identifiers.Contains(s)) { found++; } } // if everything matches, we can be sure that this is the correct ban record/player so we can unban. if (found == ban.identifiers.Count && ban.playerName == record.playerName && ban.bannedBy == record.bannedBy && ban.banReason == record.banReason && ban.bannedUntil.ToString() == record.bannedUntil.ToString()) { itemsToRemove.Add(BannedPlayersList.IndexOf(ban)); } } } for (var i = BannedPlayersList.Count; i > 0; i--) { if (itemsToRemove.Contains(i - 1) && i - 1 >= 0 && i - 1 < BannedPlayersList.Count) { BannedPlayersList.RemoveAt(i - 1); } } var output = JsonConvert.SerializeObject(BannedPlayersList, Formatting.Indented); while (readingOrWritingToBanFile) { await Delay(0); } readingOrWritingToBanFile = true; bool result = SaveResourceFile(GetCurrentResourceName(), "bans.json", output, -1); readingOrWritingToBanFile = false; return(result); }
/// <summary> /// Bans the specified player from the server. /// </summary> /// <param name="source">The player who triggered the event.</param> /// <param name="targetPlayer">The player that needs to be banned.</param> /// <param name="banReason">The reason why the player is getting banned.</param> private async void BanPlayer([FromSource] Player source, int targetPlayer, string banReason) { if (IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.PermBan") || IsPlayerAceAllowed(source.Handle, "vMenu.Everything") || IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.All")) { Player target = new PlayerList()[targetPlayer]; if (target != null) { if (!IsPlayerAceAllowed(target.Handle, "vMenu.DontBanMe")) { BanRecord ban = new BanRecord() { bannedBy = GetSafePlayerName(source.Name), bannedUntil = new DateTime(3000, 1, 1), banReason = banReason, identifiers = target.Identifiers.ToList <string>(), playerName = GetSafePlayerName(target.Name) }; if (await AddBan(ban)) { BanLog($"A new ban record has been added. Player: '{ban.playerName}' was banned by '{ban.bannedBy}' " + $"for '{ban.banReason}' until '{ban.bannedUntil}' (forever)."); target.Drop($"You have been permanently banned from this server. Banned by: {ban.bannedBy}. Ban reason: {ban.banReason}"); TriggerEvent("vMenu:BanSuccessful", JsonConvert.SerializeObject(ban).ToString()); source.TriggerEvent("vMenu:Notify", "~g~Target player successfully banned."); BannedPlayersList = await GetBanList(); } else { Log("Saving of new ban failed. Reason: unknown. Maybe the file is broken?\n", LogLevel.error); } } else { Log("Could not ban player because they are exempt from being banned.", LogLevel.error); source.TriggerEvent("vMenu:Notify", "~r~Could not ban this player, they are exempt from being banned."); } return; } Log("An error occurred while trying to ban someone. Error details: The specified target player is 'null', unknown reason.", LogLevel.error); TriggerClientEvent(player: source, eventName: "vMenu:Notify", args: "An unknown error occurred. Report it here: vespura.com/vmenu"); } else { BanCheater(source); } }
public static void loadBans(ConfigStore Store) { string FileName = SERVER_BANS_FILENAME; try { if (File.Exists(FileName)) { Store.bans.Clear(); foreach (var l in File.ReadAllLines(FileName)) { var Now = DateTime.Now; try { if (l.StartsWith("#")) { continue; } var parts = l.Split('\t'); var newBan = new BanRecord() { When = DateTime.Parse(parts[0]), Expires = DateTime.Parse(parts[1]), WhoBy = parts[2], BannedIP = IPAddress.Parse(parts[3]), BannedGUID = Guid.Parse(parts[4]), BannedName = parts[5], Why = parts[6], }; if (newBan.Expires > Now) { Store.bans.Add(newBan); } } catch { //Bad ban line. Don't care? } } } } catch { } }
/// <summary> /// Removes a ban record. /// </summary> /// <param name="source"></param> /// <param name="banRecordJsonString"></param> private void RemoveBanRecord([FromSource] Player source, string banRecordJsonString) { if (IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.Unban")) { dynamic obj = JsonConvert.DeserializeObject(banRecordJsonString); BanRecord ban = JsonToBanRecord(obj); if (RemoveBan(ban)) { BanLog($"The following ban record has been removed (player unbanned). " + $"[Player: {ban.playerName} was banned by {ban.bannedBy} for {ban.banReason} until {ban.bannedUntil}.]"); TriggerEvent("vMenu:UnbanSuccessful", JsonConvert.SerializeObject(ban).ToString()); } } else { BanCheater(source); } }
/// <summary> /// Checks if the player is banned in the SQLite database, if so then the output ban record list will be filled with all records found matching that player. /// </summary> /// <param name="source"></param> /// <param name="r"></param> /// <returns></returns> private static bool IsPlayerSqlBanned(Player source, out List <BanRecord> r) { string ids = ""; foreach (string id in source.Identifiers) { ids += $"identifiers LIKE '%{id}%' OR "; } ids = ids.Trim(' ', 'R', 'O', ' '); ids += ""; List <BanRecord> banRecordsForPlayer = new List <BanRecord>(); using (SQLiteConnection db = new SQLiteConnection($"Data Source='{bansDbFilePath}{bansDbFileName}';Version=3;")) { db.Open(); using (SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM bans WHERE {ids};", db)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { string[] identifiers = JsonConvert.DeserializeObject <string[]>(rdr.GetString(0)); string playername = rdr.GetString(1); string banreason = rdr.GetString(2); string bannedby = rdr.GetString(3); DateTime banneduntil = rdr.GetDateTime(4); var br = new BanRecord(playername, identifiers.ToList(), banneduntil, banreason, bannedby); banRecordsForPlayer.Add(br); } } } db.Close(); } if (banRecordsForPlayer.Count > 0) { r = banRecordsForPlayer; return(true); } r = new List <BanRecord>(); return(false); }
public async Task <BanRecord> AddBan(BanDto banDto) { var ban = new BanRecord { UserId = banDto?.UserId, Description = banDto.Description, ExpirationDate = banDto.ExpirationDate, }; await _context.BanRecords.AddAsync(ban).ConfigureAwait(false); await _context.SaveChangesAsync().ConfigureAwait(false); var user = await _context.Users.FirstOrDefaultAsync(u => u.Id == ban.UserId).ConfigureAwait(false); user.BanRecordId = ban.Id; await _context.SaveChangesAsync().ConfigureAwait(false); return(ban); }
/// <summary> /// Someone trying to trigger fake server events? Well, goodbye idiots. /// </summary> /// <param name="source"></param> public static void BanCheater(Player source) { var ban = new BanRecord() { bannedBy = "vMenu Auto Ban", bannedUntil = new DateTime(3000, 1, 1), banReason = "You have been automatically banned. If you believe this was done by error, please contact the server owner for support.", identifiers = source.Identifiers.ToList(), playerName = GetSafePlayerName(source.Name) }; if (AddBan(ban)) { TriggerEvent("vMenu:BanCheaterSuccessful", JsonConvert.SerializeObject(ban).ToString()); BanLog($"A cheater has been banned. {JsonConvert.SerializeObject(ban).ToString()}"); } source.TriggerEvent("vMenu:GoodBye"); // this is much more fun than just kicking them. }
/// <summary> /// Removes a ban record from the SQLite database. /// </summary> /// <param name="br"></param> private static void RemoveSqlBanRecord(BanRecord br) { string ids = ""; foreach (string id in br.identifiers) { ids += $"identifiers LIKE '%{id}%' OR "; } ids = ids.Trim(' ', 'R', 'O', ' '); ids += ""; using (SQLiteConnection db = new SQLiteConnection($"Data Source='{bansDbFilePath}{bansDbFileName}';Version=3;")) { db.Open(); using (SQLiteCommand cmd = new SQLiteCommand($"DELETE FROM bans WHERE {ids};", db)) { cmd.ExecuteNonQuery(); } db.Close(); } }
/// <summary> /// Bans the specified player for a the specified amount of hours. /// </summary> /// <param name="source">Player who triggered the event.</param> /// <param name="targetPlayer">Player who needs to be banned.</param> /// <param name="banDurationHours">Ban duration in hours.</param> /// <param name="banReason">Reason for the ban.</param> private void BanPlayer([FromSource] Player source, int targetPlayer, double banDurationHours, string banReason) { if (IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.TempBan") || IsPlayerAceAllowed(source.Handle, "vMenu.Everything") || IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.All")) { Player target = new PlayerList()[targetPlayer]; if (!IsPlayerAceAllowed(target.Handle, "vMenu.DontBanMe")) { BanRecord ban = new BanRecord() { bannedBy = GetSafePlayerName(source.Name), bannedUntil = DateTime.Now.AddHours(banDurationHours <= 720.0 ? banDurationHours : 720.0), banReason = banReason, identifiers = target.Identifiers.ToList <string>(), playerName = GetSafePlayerName(target.Name) }; if (AddBan(ban)) { BanLog($"A new ban record has been added. Player: {ban.playerName} was banned by " + $"{ban.bannedBy} for {ban.banReason} until {ban.bannedUntil}."); TriggerEvent("vMenu:BanSuccessful", JsonConvert.SerializeObject(ban).ToString()); } else { if (MainServer.debug) { Debug.Write("Saving of new ban failed. Reason: unknown. Maybe the file is broken?"); } } BannedPlayersList = GetBanList(); string timeRemaining = GetRemainingTimeMessage(ban.bannedUntil.Subtract(DateTime.Now)); target.Drop($"You are banned from this server. Ban time remaining: {timeRemaining}" + $". Banned by: {ban.bannedBy}. Ban reason: {ban.banReason}"); } } else { BanCheater(source); } }
/// <summary> /// Converts a json object into a BanRecord struct. /// </summary> /// <param name="br"></param> /// <returns></returns> private static BanRecord JsonToBanRecord(dynamic br) { var newBr = new BanRecord(); foreach (Newtonsoft.Json.Linq.JProperty brValue in br) { string key = brValue.Name.ToString(); var value = brValue.Value; if (key == "playerName") { newBr.playerName = value.ToString(); if (string.IsNullOrEmpty(newBr.playerName)) { newBr.playerName = "(invalid or no name)"; } } else if (key == "identifiers") { var tmpList = new List <string>(); foreach (string identifier in value) { tmpList.Add(identifier); } newBr.identifiers = tmpList; } else if (key == "bannedUntil") { newBr.bannedUntil = DateTime.Parse(value.ToString()); } else if (key == "banReason") { newBr.banReason = value.ToString(); } else if (key == "bannedBy") { newBr.bannedBy = value.ToString(); } } return(newBr); }
/// <summary> /// Bans the specified player from the server. /// </summary> /// <param name="source">The player who triggered the event.</param> /// <param name="targetPlayer">The player that needs to be banned.</param> /// <param name="banReason">The reason why the player is getting banned.</param> private void BanPlayer([FromSource] Player source, int targetPlayer, string banReason) { if (IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.PermBan") || IsPlayerAceAllowed(source.Handle, "vMenu.Everything") || IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.All")) { Player target = new PlayerList()[targetPlayer]; if (!IsPlayerAceAllowed(target.Handle, "vMenu.DontBanMe")) { BanRecord ban = new BanRecord() { bannedBy = GetSafePlayerName(source.Name), bannedUntil = new DateTime(3000, 1, 1), banReason = banReason, identifiers = target.Identifiers.ToList <string>(), playerName = GetSafePlayerName(target.Name) }; if (AddBan(ban)) { BanLog($"A new ban record has been added. Player: {ban.playerName} was banned by {ban.bannedBy} " + $"for {ban.banReason} until {ban.bannedUntil} (forever)."); TriggerEvent("vMenu:BanSuccessful", JsonConvert.SerializeObject(ban).ToString()); } else { if (MainServer.debug) { Debug.Write("Saving of new ban failed. Reason: unknown. Maybe the file is broken?"); } } BannedPlayersList = GetBanList(); target.Drop($"You have been permanently banned from this server. " + $"Banned by: {ban.bannedBy}. Ban reason: {ban.banReason}"); } } else { BanCheater(source); } }
/// <summary> /// Removes a ban record from the banned players list. /// </summary> /// <param name="record"></param> /// <returns></returns> public static bool RemoveBan(BanRecord record) { BannedPlayersList = GetBanList(); List <int> itemsToRemove = new List <int>(); foreach (BanRecord ban in BannedPlayersList) { if (!itemsToRemove.Contains(BannedPlayersList.IndexOf(ban))) { var found = 0; foreach (string s in ban.identifiers) { if (record.identifiers.Contains(s)) { found++; } } // if everything matches, we can be sure that this is the correct ban record/player so we can unban. if (found == ban.identifiers.Count && ban.playerName == record.playerName && ban.bannedBy == record.bannedBy && ban.banReason == record.banReason && ban.bannedUntil.ToString() == record.bannedUntil.ToString()) { itemsToRemove.Add(BannedPlayersList.IndexOf(ban)); } } } for (var i = BannedPlayersList.Count; i > 0; i--) { if (itemsToRemove.Contains(i - 1) && i - 1 >= 0 && i - 1 < BannedPlayersList.Count) { BannedPlayersList.RemoveAt(i - 1); } } var output = JsonConvert.SerializeObject(BannedPlayersList); return(SaveResourceFile(GetCurrentResourceName(), "bans.json", output, output.Length)); }
/// <summary> /// Creates the menu. /// </summary> private void CreateMenu() { menu = new Menu(Game.Player.Name, "Banned Players Management"); bannedPlayer.AddMenuItem(new MenuItem("Player Name")); bannedPlayer.AddMenuItem(new MenuItem("Banned By")); bannedPlayer.AddMenuItem(new MenuItem("Banned Until")); bannedPlayer.AddMenuItem(new MenuItem("Player Identifiers")); bannedPlayer.AddMenuItem(new MenuItem("Banned For")); bannedPlayer.AddMenuItem(new MenuItem("~r~Unban", "~r~Warning, unbanning the player can NOT be undone. You will NOT be able to ban them agian until they re-join the server. Are you absolutely sure you want to unban this player? ~s~Tip: Tempbanned players will automatically get unbanned if they log on to the server after their ban date has expired.")); // should be enough for now to cover all possible identifiers. List <string> colors = new List <string>() { "~r~", "~g~", "~b~", "~o~", "~y~", "~p~", "~s~", "~t~", }; bannedPlayer.OnMenuClose += (sender) => { BaseScript.TriggerServerEvent("vMenu:RequestBanList", Game.Player.Handle); bannedPlayer.GetMenuItems()[5].Label = ""; UpdateBans(); }; bannedPlayer.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) => { bannedPlayer.GetMenuItems()[5].Label = ""; }; bannedPlayer.OnItemSelect += (sender, item, index) => { if (index == 5 && IsAllowed(Permission.OPUnban)) { if (item.Label == "Are you sure?") { if (banlist.Contains(currentRecord)) { UnbanPlayer(banlist.IndexOf(currentRecord)); bannedPlayer.GetMenuItems()[5].Label = ""; bannedPlayer.GoBack(); } else { Notify.Error("Somehow you managed to click the unban button but this ban record you're apparently viewing does not even exist. Weird..."); } } else { item.Label = "Are you sure?"; } } else { bannedPlayer.GetMenuItems()[5].Label = ""; } }; menu.OnItemSelect += (sender, item, index) => { if (index < banlist.Count) { currentRecord = banlist[index]; bannedPlayer.MenuSubtitle = "Ban Record: ~y~" + currentRecord.playerName; var nameItem = bannedPlayer.GetMenuItems()[0]; var bannedByItem = bannedPlayer.GetMenuItems()[1]; var bannedUntilItem = bannedPlayer.GetMenuItems()[2]; var playerIdentifiersItem = bannedPlayer.GetMenuItems()[3]; var banReasonItem = bannedPlayer.GetMenuItems()[4]; nameItem.Label = currentRecord.playerName; nameItem.Description = "Player name: ~y~" + currentRecord.playerName; bannedByItem.Label = currentRecord.bannedBy; bannedByItem.Description = "Player banned by: ~y~" + currentRecord.bannedBy; if (currentRecord.bannedUntil.Date.Year == 3000) { bannedUntilItem.Label = "Forever"; } else { bannedUntilItem.Label = currentRecord.bannedUntil.Date.ToString(); } bannedUntilItem.Description = "This player is banned until: " + currentRecord.bannedUntil.Date.ToString(); playerIdentifiersItem.Description = ""; int i = 0; foreach (string id in currentRecord.identifiers) { // only (admins) people that can unban players are allowed to view IP's. // this is just a slight 'safety' feature in case someone who doesn't know what they're doing // gave builtin.everyone access to view the banlist. if (id.StartsWith("ip:") && !IsAllowed(Permission.OPUnban)) { playerIdentifiersItem.Description += $"{colors[i]}ip: (hidden) "; } else { playerIdentifiersItem.Description += $"{colors[i]}{id.Replace(":", ": ")} "; } i++; } banReasonItem.Description = "Banned for: " + currentRecord.banReason; var unbanPlayerBtn = bannedPlayer.GetMenuItems()[5]; unbanPlayerBtn.Label = ""; if (!IsAllowed(Permission.OPUnban)) { unbanPlayerBtn.Enabled = false; unbanPlayerBtn.Description = "You are not allowed to unban players. You are only allowed to view their ban record."; unbanPlayerBtn.LeftIcon = MenuItem.Icon.LOCK; } bannedPlayer.RefreshIndex(); //bannedPlayer.UpdateScaleform(); } }; MenuController.AddMenu(bannedPlayer); }
/// <summary> /// Creates the menu. /// </summary> private void CreateMenu() { menu = new Menu(Game.Player.Name, LM.Get("Banned Players Management")); menu.InstructionalButtons.Add(Control.Jump, LM.Get("Filter Options")); menu.ButtonPressHandlers.Add(new Menu.ButtonPressHandler(Control.Jump, Menu.ControlPressCheckType.JUST_RELEASED, new Action <Menu, Control>(async(a, b) => { if (banlist.Count > 1) { string filterText = await GetUserInput(LM.Get("Filter List By Username (leave this empty to reset the filter!)")); if (string.IsNullOrEmpty(filterText)) { Subtitle.Custom(LM.Get("Filters have been cleared.")); menu.ResetFilter(); UpdateBans(); } else { menu.FilterMenuItems(item => item.ItemData is BanRecord br && br.playerName.ToLower().Contains(filterText.ToLower())); Subtitle.Custom(LM.Get("Username filter has been applied.")); } } else { Notify.Error(LM.Get("At least 2 players need to be banned in order to use the filter function.")); } Log($"Button pressed: {a} {b}"); }), true)); bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Player Name"))); bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Banned By"))); bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Banned Until"))); bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Player Identifiers"))); bannedPlayer.AddMenuItem(new MenuItem(LM.Get("Banned For"))); bannedPlayer.AddMenuItem(new MenuItem(LM.Get("~r~Unban"), LM.Get("~r~Warning, unbanning the player can NOT be undone. You will NOT be able to ban them again until they re-join the server. Are you absolutely sure you want to unban this player? ~s~Tip: Tempbanned players will automatically get unbanned if they log on to the server after their ban date has expired."))); // should be enough for now to cover all possible identifiers. List <string> colors = new List <string>() { "~r~", "~g~", "~b~", "~o~", "~y~", "~p~", "~s~", "~t~", }; bannedPlayer.OnMenuClose += (sender) => { BaseScript.TriggerServerEvent("vMenu:RequestBanList", Game.Player.Handle); bannedPlayer.GetMenuItems()[5].Label = ""; UpdateBans(); }; bannedPlayer.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) => { bannedPlayer.GetMenuItems()[5].Label = ""; }; bannedPlayer.OnItemSelect += (sender, item, index) => { if (index == 5 && IsAllowed(Permission.OPUnban)) { if (item.Label == LM.Get("Are you sure?")) { if (banlist.Contains(currentRecord)) { UnbanPlayer(banlist.IndexOf(currentRecord)); bannedPlayer.GetMenuItems()[5].Label = ""; bannedPlayer.GoBack(); } else { Notify.Error(LM.Get("Somehow you managed to click the unban button but this ban record you're apparently viewing does not even exist. Weird...")); } } else { item.Label = LM.Get("Are you sure?"); } } else { bannedPlayer.GetMenuItems()[5].Label = ""; } }; menu.OnItemSelect += (sender, item, index) => { //if (index < banlist.Count) //{ currentRecord = item.ItemData; bannedPlayer.MenuSubtitle = LM.Get("Ban Record: ~y~") + currentRecord.playerName; var nameItem = bannedPlayer.GetMenuItems()[0]; var bannedByItem = bannedPlayer.GetMenuItems()[1]; var bannedUntilItem = bannedPlayer.GetMenuItems()[2]; var playerIdentifiersItem = bannedPlayer.GetMenuItems()[3]; var banReasonItem = bannedPlayer.GetMenuItems()[4]; nameItem.Label = currentRecord.playerName; nameItem.Description = LM.Get("Player name: ~y~") + currentRecord.playerName; bannedByItem.Label = currentRecord.bannedBy; bannedByItem.Description = LM.Get("Player banned by: ~y~") + currentRecord.bannedBy; if (currentRecord.bannedUntil.Date.Year == 3000) { bannedUntilItem.Label = LM.Get("Forever"); } else { bannedUntilItem.Label = currentRecord.bannedUntil.Date.ToString(); } bannedUntilItem.Description = LM.Get("This player is banned until: ") + currentRecord.bannedUntil.Date.ToString(); playerIdentifiersItem.Description = ""; int i = 0; foreach (string id in currentRecord.identifiers) { // only (admins) people that can unban players are allowed to view IP's. // this is just a slight 'safety' feature in case someone who doesn't know what they're doing // gave builtin.everyone access to view the banlist. if (id.StartsWith("ip:") && !IsAllowed(Permission.OPUnban)) { playerIdentifiersItem.Description += $"{colors[i]}ip: (hidden) "; } else { playerIdentifiersItem.Description += $"{colors[i]}{id.Replace(":", ": ")} "; } i++; } banReasonItem.Description = LM.Get("Banned for: ") + currentRecord.banReason; var unbanPlayerBtn = bannedPlayer.GetMenuItems()[5]; unbanPlayerBtn.Label = ""; if (!IsAllowed(Permission.OPUnban)) { unbanPlayerBtn.Enabled = false; unbanPlayerBtn.Description = LM.Get("You are not allowed to unban players. You are only allowed to view their ban record."); unbanPlayerBtn.LeftIcon = MenuItem.Icon.LOCK; } bannedPlayer.RefreshIndex(); //} }; MenuController.AddMenu(bannedPlayer); }
private void LogIt(BanRecord record) { WebhookManager.SendWebhook(record.Player.Name, record.Reason, Server.Hostname.RemoveColors(), "**[UiC Ban] Player Banned**", "UiC Ban System", Color.Red); }
/// <summary> /// Removes a ban record from the banned players list. /// </summary> /// <param name="record"></param> /// <returns></returns> public static void RemoveBan(BanRecord record) { DeleteResourceKvp(BAN_KVP_PREFIX + record.uuid.ToString()); bansHaveChanged = true; }
/// <summary> /// Gets the ban list from the bans.json file. /// </summary> /// <returns></returns> public static async Task <List <BanRecord> > GetBanList() { if (useJson) { while (readingOrWritingToBanFile) { await Delay(0); } readingOrWritingToBanFile = true; var banList = new List <BanRecord>(); string bansJson = LoadResourceFile(GetCurrentResourceName(), "bans.json"); if (bansJson != null && bansJson != "" && !string.IsNullOrEmpty(bansJson)) { dynamic banRecords = JsonConvert.DeserializeObject(bansJson); if (banRecords != null) { foreach (dynamic br in banRecords) { banList.Add(JsonToBanRecord(br)); } } } readingOrWritingToBanFile = false; return(banList); } else { List <BanRecord> bans = new List <BanRecord>(); using (SQLiteConnection db = new SQLiteConnection($"Data Source='{bansDbFilePath}{bansDbFileName}';Version=3;")) { db.Open(); using (SQLiteCommand cmd = new SQLiteCommand($"SELECT * FROM bans;", db)) { using (SQLiteDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { string[] identifiers = JsonConvert.DeserializeObject <string[]>(rdr.GetString(0)); string playername = rdr.GetString(1); string banreason = rdr.GetString(2); string bannedby = rdr.GetString(3); DateTime banneduntil = rdr.GetDateTime(4); var br = new BanRecord() { bannedBy = bannedby, bannedUntil = banneduntil, banReason = banreason, identifiers = identifiers.ToList(), playerName = playername }; bans.Add(br); } } } db.Close(); } return(bans); } }
/// <summary> /// Creates the menu. /// </summary> private void CreateMenu() { menu = new Menu(Game.Player.Name, "封鎖玩家管理"); menu.InstructionalButtons.Add(Control.Jump, "篩選選項"); menu.ButtonPressHandlers.Add(new Menu.ButtonPressHandler(Control.Jump, Menu.ControlPressCheckType.JUST_RELEASED, new Action <Menu, Control>(async(a, b) => { if (banlist.Count > 1) { string filterText = await GetUserInput("篩選列表(按用戶名排序)(將此保留為空以重置過濾器!)"); if (string.IsNullOrEmpty(filterText)) { Subtitle.Custom("篩選列表已清除."); menu.ResetFilter(); UpdateBans(); } else { menu.FilterMenuItems(item => item.ItemData is BanRecord br && br.playerName.ToLower().Contains(filterText.ToLower())); Subtitle.Custom("用戶名過濾已套用."); } } else { Notify.Error("要使用過濾功能,至少需要兩位以上的封鎖玩家"); } Log($"Button pressed: {a} {b}"); }), true)); bannedPlayer.AddMenuItem(new MenuItem("玩家名字")); bannedPlayer.AddMenuItem(new MenuItem("封鎖人")); bannedPlayer.AddMenuItem(new MenuItem("解封時間")); bannedPlayer.AddMenuItem(new MenuItem("玩家識別碼")); bannedPlayer.AddMenuItem(new MenuItem("封鎖理由")); bannedPlayer.AddMenuItem(new MenuItem("~r~解封", "~r~警告,禁止玩家無法撤消。 在它們重新加入服務器之前,您將無法再次禁止它們。 您確定要取消該此玩家的封鎖嗎? 〜s〜提示:如果被禁的玩家在封鎖日期結束後他們仍可以進入伺服器.")); // should be enough for now to cover all possible identifiers. List <string> colors = new List <string>() { "~r~", "~g~", "~b~", "~o~", "~y~", "~p~", "~s~", "~t~", }; bannedPlayer.OnMenuClose += (sender) => { BaseScript.TriggerServerEvent("vMenu:RequestBanList", Game.Player.Handle); bannedPlayer.GetMenuItems()[5].Label = ""; UpdateBans(); }; bannedPlayer.OnIndexChange += (sender, oldItem, newItem, oldIndex, newIndex) => { bannedPlayer.GetMenuItems()[5].Label = ""; }; bannedPlayer.OnItemSelect += (sender, item, index) => { if (index == 5 && IsAllowed(Permission.OPUnban)) { if (item.Label == "您確定嗎?") { if (banlist.Contains(currentRecord)) { UnbanPlayer(banlist.IndexOf(currentRecord)); bannedPlayer.GetMenuItems()[5].Label = ""; bannedPlayer.GoBack(); } else { Notify.Error("您設法以某種方式單擊了取消禁止按鈕,但是您顯然正在查看的禁止記錄甚至不存在..."); } } else { item.Label = "您確定嗎?"; } } else { bannedPlayer.GetMenuItems()[5].Label = ""; } }; menu.OnItemSelect += (sender, item, index) => { //if (index < banlist.Count) //{ currentRecord = item.ItemData; bannedPlayer.MenuSubtitle = "封鎖理由: ~y~" + currentRecord.playerName; var nameItem = bannedPlayer.GetMenuItems()[0]; var bannedByItem = bannedPlayer.GetMenuItems()[1]; var bannedUntilItem = bannedPlayer.GetMenuItems()[2]; var playerIdentifiersItem = bannedPlayer.GetMenuItems()[3]; var banReasonItem = bannedPlayer.GetMenuItems()[4]; nameItem.Label = currentRecord.playerName; nameItem.Description = "玩家名字: ~y~" + currentRecord.playerName; bannedByItem.Label = currentRecord.bannedBy; bannedByItem.Description = "被 ~y~" + currentRecord.bannedBy + "封鎖"; if (currentRecord.bannedUntil.Date.Year == 3000) { bannedUntilItem.Label = "永遠"; } else { bannedUntilItem.Label = currentRecord.bannedUntil.Date.ToString(); } bannedUntilItem.Description = "這個玩家將再: " + currentRecord.bannedUntil.Date.ToString() + "後解鎖"; playerIdentifiersItem.Description = ""; int i = 0; foreach (string id in currentRecord.identifiers) { // only (admins) people that can unban players are allowed to view IP's. // this is just a slight 'safety' feature in case someone who doesn't know what they're doing // gave builtin.everyone access to view the banlist. if (id.StartsWith("ip:") && !IsAllowed(Permission.OPUnban)) { playerIdentifiersItem.Description += $"{colors[i]}ip: (hidden) "; } else { playerIdentifiersItem.Description += $"{colors[i]}{id.Replace(":", ": ")} "; } i++; } banReasonItem.Description = "封鎖理由: " + currentRecord.banReason; var unbanPlayerBtn = bannedPlayer.GetMenuItems()[5]; unbanPlayerBtn.Label = ""; if (!IsAllowed(Permission.OPUnban)) { unbanPlayerBtn.Enabled = false; unbanPlayerBtn.Description = "您不能取消玩家封鎖。 您只能查看其封鎖記錄."; unbanPlayerBtn.LeftIcon = MenuItem.Icon.LOCK; } bannedPlayer.RefreshIndex(); //} }; MenuController.AddMenu(bannedPlayer); }
/// <summary> /// Bans the specified player for a the specified amount of hours. /// </summary> /// <param name="source">Player who triggered the event.</param> /// <param name="targetPlayer">Player who needs to be banned.</param> /// <param name="banDurationHours">Ban duration in hours.</param> /// <param name="banReason">Reason for the ban.</param> private async void BanPlayer([FromSource] Player source, int targetPlayer, double banDurationHours, string banReason) { if (IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.TempBan") || IsPlayerAceAllowed(source.Handle, "vMenu.Everything") || IsPlayerAceAllowed(source.Handle, "vMenu.OnlinePlayers.All")) { Log("Source player is allowed to ban others.", LogLevel.info); Player target = Players[targetPlayer]; if (target != null) { Log("Target player is not null so moving on.", LogLevel.info); if (!IsPlayerAceAllowed(target.Handle, "vMenu.DontBanMe")) { Log("Target player (Player) does not have the 'dont ban me' permission, so we can continue to ban them.", LogLevel.info); var banduration = (banDurationHours > 0 ? /* ban temporarily */ (DateTime.Now.AddHours(banDurationHours <= 720.0 ? banDurationHours : 720.0)) : /* ban forever */ (new DateTime(3000, 1, 1))); if (useJson) { BanRecord ban = new BanRecord() { bannedBy = GetSafePlayerName(source.Name), bannedUntil = banduration, banReason = banReason, identifiers = target.Identifiers.ToList(), playerName = GetSafePlayerName(target.Name) }; Log("Ban record created.", LogLevel.info); if (await AddBan(ban)) { BanLog($"A new ban record has been added. Player: '{ban.playerName}' was banned by " + $"'{ban.bannedBy}' for '{ban.banReason}' until '{ban.bannedUntil}'."); TriggerEvent("vMenu:BanSuccessful", JsonConvert.SerializeObject(ban).ToString()); BannedPlayersList = await GetBanList(); string timeRemaining = GetRemainingTimeMessage(ban.bannedUntil.Subtract(DateTime.Now)); target.Drop($"You are banned from this server. Ban time remaining: {timeRemaining}. Banned by: {ban.bannedBy}. Ban reason: {ban.banReason}"); source.TriggerEvent("vMenu:Notify", "~g~Target player successfully temp banned."); } else { Log("Saving of new ban failed. Reason: unknown. Maybe the file is broken?", LogLevel.error); source.TriggerEvent("vMenu:Notify", "~r~Could not ban the target player, reason: unknown."); } } else { BanRecord br = new BanRecord(GetSafePlayerName(source.Name), target.Identifiers.ToList(), banduration, banReason, GetSafePlayerName(target.Name)); if (AddSqlBan(br)) { BanLog($"A new ban record has been added. Player: '{br.playerName}' was banned by " + $"'{br.bannedBy}' for '{br.banReason}' until '{br.bannedUntil}'."); TriggerEvent("vMenu:BanSuccessful", JsonConvert.SerializeObject(br).ToString()); BannedPlayersList = await GetBanList(); string timeRemaining = GetRemainingTimeMessage(br.bannedUntil.Subtract(DateTime.Now)); target.Drop($"You are banned from this server. Ban time remaining: {timeRemaining}. Banned by: {br.bannedBy}. Ban reason: {br.banReason}"); source.TriggerEvent("vMenu:Notify", "~g~Target player successfully temp banned."); } else { Log("Saving of new ban failed. Reason: unknown. Maybe the file is broken?", LogLevel.error); source.TriggerEvent("vMenu:Notify", "~r~Could not ban the target player, reason: unknown."); } } } else { Log("Player could not be banned because he is exempt from being banned.", LogLevel.error); source.TriggerEvent("vMenu:Notify", "~r~Could not ban this player, they are exempt from being banned."); } } else { Log("Player is invalid (no longer online) and therefor the banning has failed.", LogLevel.error); source.TriggerEvent("vMenu:Notify", "Could not temp-ban this player because they already left the server."); } } else { Log("If enabled, the source player will be banned now because they are cheating!", LogLevel.warning); BanCheater(source); } }