upstream ~ v1.7.7-alpha

This commit is contained in:
Sachin 2025-05-25 13:17:22 +05:30
commit c586dd700c
43 changed files with 928 additions and 337 deletions

View file

@ -145,7 +145,7 @@ internal class BanManager(Database.Database? database)
{
string sql;
if (CS2_SimpleAdmin.Instance.Config.OtherSettings.CheckMultiAccountsByIp)
if (CS2_SimpleAdmin.Instance.Config.OtherSettings.CheckMultiAccountsByIp && !CS2_SimpleAdmin.Instance.Config.OtherSettings.IgnoredIps.Contains(player.IpAddress))
{
sql = CS2_SimpleAdmin.Instance.Config.MultiServerMode ? """
SELECT COALESCE((
@ -232,7 +232,8 @@ internal class BanManager(Database.Database? database)
{
PlayerSteamID = player.SteamId.SteamId64.ToString(),
PlayerIP = CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType == 0 ||
string.IsNullOrEmpty(player.IpAddress)
string.IsNullOrEmpty(player.IpAddress) ||
CS2_SimpleAdmin.Instance.Config.OtherSettings.IgnoredIps.Contains(player.IpAddress)
? null
: player.IpAddress,
PlayerName = !string.IsNullOrEmpty(player.Name) ? player.Name : string.Empty,
@ -393,7 +394,7 @@ internal class BanManager(Database.Database? database)
{
SteamIDs = steamIds,
IpAddresses = checkIpBans ? ipAddresses : [],
ServerId = CS2_SimpleAdmin.ServerId
CS2_SimpleAdmin.ServerId
});
var valueTuples = bannedPlayers.ToList();

View file

@ -0,0 +1,397 @@
using System.Collections.Concurrent;
using CS2_SimpleAdmin.Models;
using Dapper;
using ZLinq;
namespace CS2_SimpleAdmin.Managers;
internal class CacheManager: IDisposable
{
private readonly ConcurrentDictionary<int, BanRecord> _banCache = [];
private readonly ConcurrentDictionary<string, List<BanRecord>> _steamIdIndex = [];
private readonly ConcurrentDictionary<uint, List<BanRecord>> _ipIndex = [];
private readonly ConcurrentDictionary<ulong, HashSet<IpRecord>> _playerIpsCache = [];
private HashSet<uint> _cachedIgnoredIps = [];
private DateTime _lastUpdateTime = DateTime.MinValue;
private bool _isInitialized;
private bool _disposed;
public async Task InitializeCacheAsync()
{
if (CS2_SimpleAdmin.Database == null) return;
if (!CS2_SimpleAdmin.ServerLoaded) return;
if (_isInitialized) return;
try
{
Clear();
_cachedIgnoredIps = new HashSet<uint>(
CS2_SimpleAdmin.Instance.Config.OtherSettings.IgnoredIps
.Select(IpHelper.IpToUint));
await using var connection = await CS2_SimpleAdmin.Database.GetConnectionAsync();
List<BanRecord> bans;
if (CS2_SimpleAdmin.Instance.Config.MultiServerMode)
{
bans = (await connection.QueryAsync<BanRecord>(
"""
SELECT
id AS Id,
player_steamid AS PlayerSteamId,
player_ip AS PlayerIp,
status AS Status
FROM sa_bans
""")).ToList();
}
else
{
bans = (await connection.QueryAsync<BanRecord>(
"""
SELECT
id AS Id,
player_steamid AS PlayerSteamId,
player_ip AS PlayerIp,
status AS Status
FROM sa_bans
WHERE server_id = @serverId
""", new {serverId = CS2_SimpleAdmin.ServerId})).ToList();
}
var ipHistory =
await connection.QueryAsync<(ulong steamid, string? name, uint address, DateTime used_at)>(
"SELECT steamid, name, address, used_at FROM sa_players_ips ORDER BY used_at DESC");
foreach (var ban in bans)
{
_banCache.TryAdd(ban.Id, ban);
}
foreach (var group in ipHistory.AsValueEnumerable().GroupBy(x => x.steamid))
{
var ipSet = new HashSet<IpRecord>(
group
.GroupBy(x => x.address)
.Select(g =>
{
var latest = g.MaxBy(x => x.used_at);
return new IpRecord(
g.Key,
latest.used_at,
!string.IsNullOrEmpty(latest.name)
? latest.name
: CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"
);
}),
new IpRecordComparer()
);
_playerIpsCache.AddOrUpdate(
group.Key,
_ => ipSet,
(_, existingSet) =>
{
foreach (var ip in ipSet)
{
existingSet.Remove(ip);
existingSet.Add(ip);
}
return existingSet;
});
}
RebuildIndexes();
_lastUpdateTime = DateTime.Now.AddSeconds(-1);
_isInitialized = true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public async Task ForceReInitializeCacheAsync()
{
_isInitialized = false;
_banCache.Clear();
_playerIpsCache.Clear();
_cachedIgnoredIps.Clear();
_lastUpdateTime = DateTime.MinValue;
await InitializeCacheAsync();
}
public async Task RefreshCacheAsync()
{
if (CS2_SimpleAdmin.Database == null) return;
if (!_isInitialized) return;
try
{
await using var connection = await CS2_SimpleAdmin.Database.GetConnectionAsync();
List<BanRecord> updatedBans;
var allIds = (await connection.QueryAsync<int>("SELECT id FROM sa_bans")).ToHashSet();
if (CS2_SimpleAdmin.Instance.Config.MultiServerMode)
{
updatedBans = (await connection.QueryAsync<BanRecord>(
"""
SELECT id AS Id,
player_steamid AS PlayerSteamId,
player_ip AS PlayerIp,
status AS Status
FROM `sa_bans` WHERE updated_at > @lastUpdate OR created > @lastUpdate ORDER BY updated_at DESC
""",
new { lastUpdate = _lastUpdateTime }
)).ToList();
}
else
{
updatedBans = (await connection.QueryAsync<BanRecord>(
"""
SELECT id AS Id,
player_steamid AS PlayerSteamId,
player_ip AS PlayerIp,
status AS Status
FROM `sa_bans` WHERE (updated_at > @lastUpdate OR created > @lastUpdate) AND server_id = @serverId ORDER BY updated_at DESC
""",
new { lastUpdate = _lastUpdateTime, serverId = CS2_SimpleAdmin.ServerId }
)).ToList();
}
foreach (var id in _banCache.Keys)
{
if (allIds.Contains(id) || !_banCache.TryRemove(id, out var ban)) continue;
// Remove from steamIdIndex
if (!string.IsNullOrWhiteSpace(ban.PlayerSteamId) &&
_steamIdIndex.TryGetValue(ban.PlayerSteamId, out var steamBans))
{
steamBans.RemoveAll(b => b.Id == id);
if (steamBans.Count == 0)
_steamIdIndex.TryRemove(ban.PlayerSteamId, out _);
}
// Remove from ipIndex
if (!string.IsNullOrWhiteSpace(ban.PlayerIp) &&
IpHelper.TryConvertIpToUint(ban.PlayerIp, out var ipUInt) &&
_ipIndex.TryGetValue(ipUInt, out var ipBans))
{
ipBans.RemoveAll(b => b.Id == id);
if (ipBans.Count == 0)
_ipIndex.TryRemove(ipUInt, out _);
}
}
var ipHistory = (await connection.QueryAsync<(ulong steamid, string? name, uint address, DateTime used_at)>(
"SELECT steamid, name, address, used_at FROM sa_players_ips WHERE used_at >= @lastUpdate ORDER BY used_at DESC LIMIT 300", new {lastUpdate = _lastUpdateTime})).ToList();
foreach (var group in ipHistory.AsValueEnumerable().GroupBy(x => x.steamid))
{
var ipSet = new HashSet<IpRecord>(
group
.GroupBy(x => x.address)
.Select(g =>
{
var latest = g.MaxBy(x => x.used_at);
return new IpRecord(
g.Key,
latest.used_at,
!string.IsNullOrEmpty(latest.name)
? latest.name
: CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"
);
}),
new IpRecordComparer()
);
_playerIpsCache.AddOrUpdate(
group.Key,
_ => ipSet,
(_, existingSet) =>
{
foreach (var newEntry in ipSet)
{
existingSet.Remove(newEntry);
existingSet.Add(newEntry);
}
return existingSet;
});
}
if (updatedBans.Count == 0)
return;
foreach (var ban in updatedBans)
{
_banCache.AddOrUpdate(ban.Id, ban, (_, _) => ban);
}
RebuildIndexes();
_lastUpdateTime = DateTime.Now.AddSeconds(-1);
}
catch (Exception e)
{
// ignored
}
}
private void RebuildIndexes()
{
_steamIdIndex.Clear();
_ipIndex.Clear();
foreach (var ban in _banCache.Values)
{
if (ban.Status != "ACTIVE")
continue;
if (!string.IsNullOrWhiteSpace(ban.PlayerSteamId))
{
var steamId = ban.PlayerSteamId;
_steamIdIndex.AddOrUpdate(
steamId,
key => [ban],
(key, list) =>
{
list.Add(ban);
return list;
});
}
if (ban.PlayerIp != null &&
IpHelper.TryConvertIpToUint(ban.PlayerIp, out var ipUInt))
{
_ipIndex.AddOrUpdate(
ipUInt,
key => [ban],
(key, list) =>
{
list.Add(ban);
return list;
});
}
}
}
public List<BanRecord> GetAllBans() => _banCache.Values.ToList();
public List<BanRecord> GetActiveBans() => _banCache.Values.Where(b => b.Status == "ACTIVE").ToList();
public List<BanRecord> GetPlayerBansBySteamId(string steamId) => _steamIdIndex.TryGetValue(steamId, out var bans) ? bans : [];
public List<(ulong SteamId, DateTime UsedAt, string PlayerName)> GetAccountsByIp(string ipAddress)
{
var ipAsUint = IpHelper.IpToUint(ipAddress);
return _playerIpsCache.AsValueEnumerable()
.SelectMany(kvp => kvp.Value
.Where(entry => entry.Ip == ipAsUint)
.Select(entry => (kvp.Key, entry.UsedAt, entry.PlayerName)))
.ToList();
}
private bool IsIpBanned(string ipAddress)
{
if (CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType == 0) return false;
var ipUInt = IpHelper.IpToUint(ipAddress);
return !_cachedIgnoredIps.Contains(ipUInt) && _ipIndex.ContainsKey(ipUInt);
}
public bool IsPlayerBanned(string? steamId, string? ipAddress)
{
if (steamId != null && _steamIdIndex.ContainsKey(steamId))
return true;
if (CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType == 0) return false;
if (ipAddress == null)
return false;
if (!IpHelper.TryConvertIpToUint(ipAddress, out var ipUInt))
return false;
return !_cachedIgnoredIps.Contains(ipUInt) &&
_ipIndex.ContainsKey(ipUInt);
}
public bool IsPlayerOrAnyIpBanned(ulong steamId, string? ipAddress)
{
var steamIdStr = steamId.ToString();
if (_steamIdIndex.ContainsKey(steamIdStr))
return true;
if (CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType == 0) return false;
if (!_playerIpsCache.TryGetValue(steamId, out var ipData))
return false;
var now = DateTime.Now;
var cutoff = now.AddDays(-7);
if (ipAddress != null)
{
var ipAsUint = IpHelper.IpToUint(ipAddress);
if (!_cachedIgnoredIps.Contains(ipAsUint))
{
ipData.Add(new IpRecord(
ipAsUint,
now.AddSeconds(-2), // artificially recent
CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown"
));
}
}
foreach (var ipRecord in ipData)
{
if (ipRecord.UsedAt < cutoff || _cachedIgnoredIps.Contains(ipRecord.Ip))
continue;
if (_ipIndex.ContainsKey(ipRecord.Ip))
return true;
}
return false;
}
public bool HasIpForPlayer(ulong steamId, string ipAddress)
{
if (string.IsNullOrWhiteSpace(ipAddress))
return false;
return _playerIpsCache.TryGetValue(steamId, out var ipData)
&& ipData.Any(x => x.Ip == IpHelper.IpToUint(ipAddress));
}
private void Clear()
{
_steamIdIndex.Clear();
_ipIndex.Clear();
_banCache.Clear();
_playerIpsCache.Clear();
_cachedIgnoredIps.Clear();
}
public void Dispose()
{
if (_disposed) return;
Clear();
_disposed = true;
}
}
public class IpRecordComparer : IEqualityComparer<IpRecord>
{
public bool Equals(IpRecord x, IpRecord y)
=> x.Ip == y.Ip;
public int GetHashCode(IpRecord obj)
=> obj.Ip.GetHashCode();
}

View file

@ -187,13 +187,13 @@ internal class MuteManager(Database.Database? database)
}
}
public async Task CheckOnlineModeMutes(List<(string? IpAddress, ulong SteamID, int? UserId, int Slot)> players)
public async Task CheckOnlineModeMutes(List<(ulong SteamID, int? UserId, int Slot)> players)
{
if (database == null) return;
try
{
var batchSize = 10;
const int batchSize = 20;
await using var connection = await database.GetConnectionAsync();
var sql = CS2_SimpleAdmin.Instance.Config.MultiServerMode
@ -205,7 +205,7 @@ internal class MuteManager(Database.Database? database)
var batch = players.Skip(i).Take(batchSize);
var parametersList = new List<object>();
foreach (var (_, steamId, _, _) in batch)
foreach (var (steamId, _, _) in batch)
{
parametersList.Add(new { PlayerSteamID = steamId, serverid = CS2_SimpleAdmin.ServerId });
}
@ -218,7 +218,7 @@ internal class MuteManager(Database.Database? database)
: "SELECT * FROM `sa_mutes` WHERE player_steamid = @PlayerSteamID AND passed >= duration AND duration > 0 AND status = 'ACTIVE' AND server_id = @serverid";
foreach (var (_, steamId, _, slot) in players)
foreach (var (steamId, _, slot) in players)
{
var muteRecords = await connection.QueryAsync(sql, new { PlayerSteamID = steamId, serverid = CS2_SimpleAdmin.ServerId });

View file

@ -6,6 +6,7 @@ using Microsoft.Extensions.Logging;
using MySqlConnector;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using CounterStrikeSharp.API.Modules.Admin;
namespace CS2_SimpleAdmin.Managers;
@ -13,7 +14,8 @@ public class PermissionManager(Database.Database? database)
{
// Unused for now
//public static readonly ConcurrentDictionary<string, ConcurrentBag<string>> _adminCache = new ConcurrentDictionary<string, ConcurrentBag<string>>();
public static readonly ConcurrentDictionary<SteamID, DateTime?> AdminCache = new();
// public static readonly ConcurrentDictionary<SteamID, DateTime?> AdminCache = new();
public static readonly ConcurrentDictionary<SteamID, (DateTime? ExpirationTime, List<string> Flags)> AdminCache = new();
// Get the relevant server groups from the sa_servers_groups table by searching if the serverId is in the servers set column
public async Task<List<string>> GetServerGroups()
@ -236,7 +238,7 @@ public class PermissionManager(Database.Database? database)
{
if (!AdminCache.ContainsKey(steamId))
{
AdminCache.TryAdd(steamId, ends);
AdminCache.TryAdd(steamId, (ends, flags));
//_adminCacheTimestamps.Add(steamId, ends);
}
@ -400,7 +402,7 @@ public class PermissionManager(Database.Database? database)
.GroupBy(player => player.name) // Group by player name
.ToDictionary(
group => group.Key, // Use the player name as the key
group =>
object (group) =>
{
// Consolidate data for players with the same name
var consolidatedData = group.Aggregate(
@ -431,17 +433,77 @@ public class PermissionManager(Database.Database? database)
return acc;
});
foreach (var player in group)
Server.NextFrameAsync(() =>
{
SteamID.TryParse(player.identity, out var steamId);
if (steamId != null && !AdminCache.ContainsKey(steamId))
{
AdminCache.TryAdd(steamId, player.ends);
}
}
var keysToRemove = new List<SteamID>();
return (object)consolidatedData;
foreach (var steamId in AdminCache.Keys.ToList())
{
var data = AdminManager.GetPlayerAdminData(steamId);
if (data != null)
{
var flagsArray = AdminCache[steamId].Flags.ToArray();
AdminManager.RemovePlayerPermissions(steamId, flagsArray);
AdminManager.RemovePlayerFromGroup(steamId, true, flagsArray);
}
keysToRemove.Add(steamId);
}
foreach (var steamId in keysToRemove)
{
if (!AdminCache.TryRemove(steamId, out _)) continue;
var data = AdminManager.GetPlayerAdminData(steamId);
if (data == null) continue;
if (data.Flags.Count != 0 && data.Groups.Count != 0) continue;
AdminManager.ClearPlayerPermissions(steamId);
AdminManager.RemovePlayerAdminData(steamId);
}
foreach (var player in group)
{
if (SteamID.TryParse(player.identity, out var steamId) && steamId != null)
{
AdminCache.TryAdd(steamId, (player.ends, player.flags));
}
}
});
// Server.NextFrameAsync(() =>
// {
// for (var index = 0; index < AdminCache.Keys.ToList().Count; index++)
// {
// var steamId = AdminCache.Keys.ToList()[index];
//
// var data = AdminManager.GetPlayerAdminData(steamId);
// if (data != null)
// {
// AdminManager.RemovePlayerPermissions(steamId, AdminCache[steamId].Flags.ToArray());
// AdminManager.RemovePlayerFromGroup(steamId, true, AdminCache[steamId].Flags.ToArray());
// }
//
// if (!AdminCache.TryRemove(steamId, out _)) continue;
//
// if (data == null) continue;
// if (data.Flags.ToList().Count != 0 && data.Groups.ToList().Count != 0)
// continue;
//
// AdminManager.ClearPlayerPermissions(steamId);
// AdminManager.RemovePlayerAdminData(steamId);
// }
//
// foreach (var player in group)
// {
// SteamID.TryParse(player.identity, out var steamId);
// if (steamId == null) continue;
// AdminCache.TryAdd(steamId, (player.ends, player.flags));
// }
// });
return consolidatedData;
});
var json = JsonConvert.SerializeObject(jsonData, Formatting.Indented);

View file

@ -7,6 +7,7 @@ using CounterStrikeSharp.API.ValveConstants.Protobuf;
using CS2_SimpleAdminApi;
using Dapper;
using Microsoft.Extensions.Logging;
using ZLinq;
namespace CS2_SimpleAdmin.Managers;
@ -26,9 +27,9 @@ public class PlayerManager
}
var ipAddress = player.IpAddress?.Split(":")[0];
CS2_SimpleAdmin.PlayersInfo[player.UserId.Value] =
new PlayerInfo(player.UserId.Value, player.Slot, new SteamID(player.SteamID), player.PlayerName, ipAddress);
// if (!player.UserId.HasValue)
// {
@ -37,35 +38,48 @@ public class PlayerManager
// }
var userId = player.UserId.Value;
// Check if the player's IP or SteamID is in the bannedPlayers list
if (_config.OtherSettings.BanType > 0 && CS2_SimpleAdmin.BannedPlayers.Contains(ipAddress) ||
CS2_SimpleAdmin.BannedPlayers.Contains(player.SteamID.ToString()))
if (!CS2_SimpleAdmin.PlayersInfo.ContainsKey(userId))
{
// Kick the player if banned
Helper.KickPlayer(player.UserId.Value, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_BANNED);
return;
Helper.KickPlayer(userId, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_INVALIDCONNECTION);
}
var steamId64 = CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64;
var steamId = steamId64.ToString();
if (CS2_SimpleAdmin.Database == null) return;
// Perform asynchronous database operations within a single method
Task.Run(async () =>
{
if (_config.OtherSettings.CheckMultiAccountsByIp)
var isBanned = CS2_SimpleAdmin.Instance.CacheManager != null && CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType switch
{
0 => CS2_SimpleAdmin.Instance.CacheManager.IsPlayerBanned(steamId, null),
_ => CS2_SimpleAdmin.Instance.Config.OtherSettings.CheckMultiAccountsByIp
? CS2_SimpleAdmin.Instance.CacheManager.IsPlayerOrAnyIpBanned(steamId64, ipAddress)
: CS2_SimpleAdmin.Instance.CacheManager.IsPlayerBanned(steamId, ipAddress)
};
if (isBanned)
{
// Kick the player if banned
await Server.NextFrameAsync(() =>
{
if (!player.UserId.HasValue) return;
Helper.KickPlayer(userId, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_BANNED);
});
return;
}
if (_config.OtherSettings.CheckMultiAccountsByIp && ipAddress != null)
{
try
{
await using var connection = await CS2_SimpleAdmin.Database.GetConnectionAsync();
const string selectQuery = "SELECT COUNT(*) FROM `sa_players_ips` WHERE steamid = @SteamID AND address = @IPAddress;";
var recordExists = await connection.ExecuteScalarAsync<int>(selectQuery, new
{
SteamID = CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64,
IPAddress = ipAddress
});
if (recordExists > 0)
if (CS2_SimpleAdmin.Instance.CacheManager != null && CS2_SimpleAdmin.Instance.CacheManager.HasIpForPlayer(
CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64, ipAddress))
{
await using var connection = await CS2_SimpleAdmin.Database.GetConnectionAsync();
const string updateQuery = """
UPDATE `sa_players_ips`
SET used_at = CURRENT_TIMESTAMP
@ -74,20 +88,46 @@ public class PlayerManager
await connection.ExecuteAsync(updateQuery, new
{
SteamID = CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64,
IPAddress = ipAddress
IPAddress = IpHelper.IpToUint(ipAddress)
});
}
else
{
const string insertQuery = """
INSERT INTO `sa_players_ips` (steamid, address, used_at)
VALUES (@SteamID, @IPAddress, CURRENT_TIMESTAMP);
""";
await connection.ExecuteAsync(insertQuery, new
await using var connection = await CS2_SimpleAdmin.Database.GetConnectionAsync();
const string selectQuery =
"SELECT COUNT(*) FROM `sa_players_ips` WHERE steamid = @SteamID AND address = @IPAddress;";
var recordExists = await connection.ExecuteScalarAsync<int>(selectQuery, new
{
SteamID = CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64,
IPAddress = ipAddress
IPAddress = IpHelper.IpToUint(ipAddress)
});
if (recordExists > 0)
{
const string updateQuery = """
UPDATE `sa_players_ips`
SET used_at = CURRENT_TIMESTAMP
WHERE steamid = @SteamID AND address = @IPAddress;
""";
await connection.ExecuteAsync(updateQuery, new
{
SteamID = CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64,
IPAddress = IpHelper.IpToUint(ipAddress)
});
}
else
{
const string insertQuery = """
INSERT INTO `sa_players_ips` (steamid, address, used_at)
VALUES (@SteamID, @IPAddress, CURRENT_TIMESTAMP);
""";
await connection.ExecuteAsync(insertQuery, new
{
SteamID = CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64,
IPAddress = IpHelper.IpToUint(ipAddress)
});
}
}
}
catch (Exception ex)
@ -95,55 +135,29 @@ public class PlayerManager
CS2_SimpleAdmin._logger?.LogError(
$"Unable to save ip address for {CS2_SimpleAdmin.PlayersInfo[userId].Name} ({ipAddress}) {ex.Message}");
}
// Get all accounts associated to the player (ip address)
CS2_SimpleAdmin.PlayersInfo[userId].AccountsAssociated =
CS2_SimpleAdmin.Instance.CacheManager?.GetAccountsByIp(ipAddress).AsValueEnumerable().Select(x => (x.SteamId, x.PlayerName)).ToList() ?? [];
}
try
try
{
if (!CS2_SimpleAdmin.PlayersInfo.ContainsKey(userId))
{
await Server.NextFrameAsync(() => Helper.KickPlayer(userId, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_INVALIDCONNECTION));
}
// var isBanned = CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType == 0
// ? CS2_SimpleAdmin.Instance.CacheManager.IsPlayerBanned(
// CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64.ToString(), null)
// : CS2_SimpleAdmin.Instance.Config.OtherSettings.CheckMultiAccountsByIp
// ? CS2_SimpleAdmin.Instance.CacheManager.IsPlayerOrAnyIpBanned(CS2_SimpleAdmin
// .PlayersInfo[userId].SteamId.SteamId64)
// : CS2_SimpleAdmin.Instance.CacheManager.IsPlayerBanned(CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64.ToString(), ipAddress);
// Check if the player is banned
var isBanned = await CS2_SimpleAdmin.Instance.BanManager.IsPlayerBanned(CS2_SimpleAdmin.PlayersInfo[userId]);
if (isBanned)
{
// Add player's IP and SteamID to bannedPlayers list if not already present
if (_config.OtherSettings.BanType > 0 && ipAddress != null &&
!CS2_SimpleAdmin.BannedPlayers.Contains(ipAddress))
{
CS2_SimpleAdmin.BannedPlayers.Add(ipAddress);
}
if (!CS2_SimpleAdmin.BannedPlayers.Contains(CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64.ToString()))
{
CS2_SimpleAdmin.BannedPlayers.Add(CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64.ToString());
}
// Kick the player if banned
await Server.NextFrameAsync(() =>
{
var victim = Utilities.GetPlayerFromUserid(userId);
if (victim == null || !victim.UserId.HasValue) return;
if (CS2_SimpleAdmin.UnlockedCommands && _config.BanIDBan)
Server.ExecuteCommand($"banid 1 {userId}");
Helper.KickPlayer(userId, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_BANNED);
});
return;
}
if (fullConnect || !fullConnect) // Temp skip
{
var warns = await CS2_SimpleAdmin.Instance.WarnManager.GetPlayerWarns(CS2_SimpleAdmin.PlayersInfo[userId], false);
var (totalMutes, totalGags, totalSilences) =
await CS2_SimpleAdmin.Instance.MuteManager.GetPlayerMutes(CS2_SimpleAdmin.PlayersInfo[userId]);
CS2_SimpleAdmin.PlayersInfo[userId].TotalBans =
await CS2_SimpleAdmin.Instance.BanManager.GetPlayerBans(CS2_SimpleAdmin.PlayersInfo[userId]);
CS2_SimpleAdmin.PlayersInfo[userId].TotalBans = CS2_SimpleAdmin.Instance.CacheManager?.GetPlayerBansBySteamId(CS2_SimpleAdmin.PlayersInfo[userId].SteamId.SteamId64.ToString()).Count ?? 0;
CS2_SimpleAdmin.PlayersInfo[userId].TotalMutes = totalMutes;
CS2_SimpleAdmin.PlayersInfo[userId].TotalGags = totalGags;
CS2_SimpleAdmin.PlayersInfo[userId].TotalSilences = totalSilences;
@ -192,6 +206,8 @@ public class PlayerManager
if (CS2_SimpleAdmin.Instance.Config.OtherSettings.NotifyPenaltiesToAdminOnConnect && fullConnect)
{
var associatedAcccountsChunks = CS2_SimpleAdmin.PlayersInfo[userId].AccountsAssociated.ChunkBy(5).ToList();
await Server.NextFrameAsync(() =>
{
foreach (var admin in Helper.GetValidPlayers()
@ -199,9 +215,8 @@ public class PlayerManager
AdminManager.PlayerHasPermissions(new SteamID(p.SteamID), "@css/ban")) &&
p.Connected == PlayerConnectedState.PlayerConnected && !CS2_SimpleAdmin.AdminDisabledJoinComms.Contains(p.SteamID)))
{
if (CS2_SimpleAdmin._localizer != null && admin != player
&& (CS2_SimpleAdmin.PlayersInfo[userId].TotalBans > 0 || CS2_SimpleAdmin.PlayersInfo[userId].TotalGags > 0 || CS2_SimpleAdmin.PlayersInfo[userId].TotalMutes > 0 || CS2_SimpleAdmin.PlayersInfo[userId].TotalSilences > 0 || CS2_SimpleAdmin.PlayersInfo[userId].TotalWarns > 0)
)
if (CS2_SimpleAdmin._localizer != null && admin != player)
{
admin.SendLocalizedMessage(CS2_SimpleAdmin._localizer, "sa_admin_penalty_info",
player.PlayerName,
CS2_SimpleAdmin.PlayersInfo[userId].TotalBans,
@ -210,6 +225,16 @@ public class PlayerManager
CS2_SimpleAdmin.PlayersInfo[userId].TotalSilences,
CS2_SimpleAdmin.PlayersInfo[userId].TotalWarns
);
foreach (var chunk in associatedAcccountsChunks)
{
admin.SendLocalizedMessage(CS2_SimpleAdmin._localizer, "sa_admin_associated_accounts",
player.PlayerName,
string.Join(", ",
chunk.Select(a => $"{a.PlayerName} ({a.SteamId})"))
);
}
}
}
});
}
@ -231,13 +256,10 @@ public class PlayerManager
CS2_SimpleAdmin.Instance.AddTimer(0.1f, () =>
{
if (CS2_SimpleAdmin.GravityPlayers.Count <= 0) return;
foreach (var value in CS2_SimpleAdmin.GravityPlayers)
{
if (value.Key is not
{ IsValid: true, Connected: PlayerConnectedState.PlayerConnected, PawnIsAlive: true })
continue;
foreach (var value in CS2_SimpleAdmin.GravityPlayers.Where(value => value.Key is
{ IsValid: true, Connected: PlayerConnectedState.PlayerConnected } || value.Key.PlayerPawn?.Value?.LifeState != (int)LifeState_t.LIFE_ALIVE))
{
value.Key.SetGravity(value.Value);
}
}, TimerFlags.REPEAT);
@ -250,88 +272,79 @@ public class PlayerManager
if (CS2_SimpleAdmin.Database == null)
return;
var players = Helper.GetValidPlayers();
var onlinePlayers = new List<(string? IpAddress, ulong SteamID, int? UserId, int Slot)>();
// var onlinePlayers = players
// .Where(player => player.IpAddress != null)
// .Select(player => (player.IpAddress, player.SteamID, player.UserId, player.Slot))
// .ToList();
foreach (var player in players)
{
if (player.IpAddress != null)
onlinePlayers.Add((player.IpAddress, player.SteamID, player.UserId, player.Slot));
}
try
{
var expireTasks = new[]
var tempPlayers = Helper.GetValidPlayers()
.Select(p => new
{
CS2_SimpleAdmin.Instance.BanManager.ExpireOldBans(),
CS2_SimpleAdmin.Instance.MuteManager.ExpireOldMutes(),
CS2_SimpleAdmin.Instance.WarnManager.ExpireOldWarns(),
CS2_SimpleAdmin.Instance.PermissionManager.DeleteOldAdmins()
};
Task.WhenAll(expireTasks).ContinueWith(t =>
{
if (t is not { IsFaulted: true, Exception: not null }) return;
foreach (var ex in t.Exception.InnerExceptions)
{
CS2_SimpleAdmin._logger?.LogError($"Error expiring penalties: {ex.Message}");
}
});
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError("Unexpected error: {exception}", ex.Message);
}
p.SteamID, p.IpAddress, p.UserId, p.Slot,
})
.ToList();
CS2_SimpleAdmin.BannedPlayers.Clear();
if (onlinePlayers.Count > 0)
_ = Task.Run(async () =>
{
try
{
Task.Run(async () =>
var expireTasks = new Task[]
{
await CS2_SimpleAdmin.Instance.BanManager.CheckOnlinePlayers(onlinePlayers);
CS2_SimpleAdmin.Instance.BanManager.ExpireOldBans(),
CS2_SimpleAdmin.Instance.MuteManager.ExpireOldMutes(),
CS2_SimpleAdmin.Instance.WarnManager.ExpireOldWarns(),
CS2_SimpleAdmin.Instance.CacheManager?.RefreshCacheAsync() ?? Task.CompletedTask,
CS2_SimpleAdmin.Instance.PermissionManager.DeleteOldAdmins()
};
if (_config.OtherSettings.TimeMode == 0)
{
await CS2_SimpleAdmin.Instance.MuteManager.CheckOnlineModeMutes(onlinePlayers);
}
}).ContinueWith(t =>
{
if (t is not { IsFaulted: true, Exception: not null }) return;
foreach (var ex in t.Exception.InnerExceptions)
{
CS2_SimpleAdmin._logger?.LogError($"Error checking online players: {ex.Message}");
}
});
await Task.WhenAll(expireTasks);
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError($"Unexpected error: {ex.Message}");
}
}
CS2_SimpleAdmin._logger?.LogError($"Error processing players timer tasks: {ex.Message}");
if (onlinePlayers.Count <= 0) return;
{
try
if (ex is AggregateException aggregate)
{
foreach (var inner in aggregate.InnerExceptions)
{
CS2_SimpleAdmin._logger?.LogError($"Inner exception: {inner.Message}");
}
}
}
var bannedPlayers = tempPlayers.AsValueEnumerable()
.Where(player =>
{
return CS2_SimpleAdmin.Instance.CacheManager != null && CS2_SimpleAdmin.Instance.Config.OtherSettings.BanType switch
{
0 => CS2_SimpleAdmin.Instance.CacheManager.IsPlayerBanned(player.SteamID.ToString(), null),
_ =>
CS2_SimpleAdmin.Instance.CacheManager.IsPlayerBanned(player.SteamID.ToString(), player.IpAddress?.Split(":")[0])
};
})
.ToList();
foreach (var player in bannedPlayers)
{
var penalizedSlots = players
.Where(player => PlayerPenaltyManager.IsSlotInPenalties(player.Slot))
.Select(player => new
{
Player = player,
IsMuted = PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Mute, out _),
IsSilenced = PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence, out _),
IsGagged = PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag, out _)
});
if (player.UserId.HasValue)
await Server.NextFrameAsync(() => Helper.KickPlayer((int)player.UserId, NetworkDisconnectionReason.NETWORK_DISCONNECT_REJECT_BANNED));
}
var onlinePlayers = tempPlayers.AsValueEnumerable().Select(player => (player.SteamID, player.UserId, player.Slot)).ToList();
if (tempPlayers.Count == 0 || onlinePlayers.Count == 0) return;
if (_config.OtherSettings.TimeMode == 0)
{
await CS2_SimpleAdmin.Instance.MuteManager.CheckOnlineModeMutes(onlinePlayers);
}
});
try
{
var players = Helper.GetValidPlayers();
var penalizedSlots = players
.Where(player => PlayerPenaltyManager.IsSlotInPenalties(player.Slot))
.Select(player => new
{
Player = player,
IsMuted = PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Mute, out _),
IsSilenced = PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Silence, out _),
IsGagged = PlayerPenaltyManager.IsPenalized(player.Slot, PenaltyType.Gag, out _)
});
foreach (var entry in penalizedSlots)
{
@ -344,14 +357,13 @@ public class PlayerManager
}
}
PlayerPenaltyManager.RemoveExpiredPenalties();
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError($"Unable to remove old penalties: {ex.Message}");
}
PlayerPenaltyManager.RemoveExpiredPenalties();
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogError($"Unable to remove old penalties: {ex.Message}");
}
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT);
}, TimerFlags.REPEAT);
}
}

View file

@ -9,9 +9,9 @@ public class ServerManager
{
private int _getIpTryCount;
public void CheckHibernationStatus()
public static void CheckHibernationStatus()
{
ConVar? convar = ConVar.Find("sv_hibernate_when_empty");
var convar = ConVar.Find("sv_hibernate_when_empty");
if (convar == null || !convar.GetPrimitiveValue<bool>())
return;
@ -95,6 +95,8 @@ public class ServerManager
new { address });
CS2_SimpleAdmin.ServerId = serverId;
CS2_SimpleAdmin._logger?.LogInformation("Loaded server with ip {ip}", ipAddress);
if (CS2_SimpleAdmin.ServerId != null)
{
@ -102,6 +104,8 @@ public class ServerManager
}
CS2_SimpleAdmin.ServerLoaded = true;
if (CS2_SimpleAdmin.Instance.CacheManager != null)
await CS2_SimpleAdmin.Instance.CacheManager.InitializeCacheAsync();
}
catch (Exception ex)
{