Skip to content

Commit

Permalink
1.4.0a
Browse files Browse the repository at this point in the history
- Ability to set the plugin mode (MultiServerMode) - When its `true`, then plugin respects penalties from all servers, when its `false` then plugin respects penalties only from this server
- Renamed command `css_reladmin` to `css_reloadadmins` (It reload admins and groups)
- Groups
  • Loading branch information
daffyyyy committed Apr 25, 2024
1 parent 270b36f commit 1cfff86
Show file tree
Hide file tree
Showing 9 changed files with 448 additions and 37 deletions.
95 changes: 93 additions & 2 deletions Commands/basecommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,97 @@ public void RemoveAdmin(CCSPlayerController? caller, string steamid, bool global
Server.PrintToConsole(msg);
}

[ConsoleCommand("css_reladmin")]
[ConsoleCommand("css_addgroup")]
[CommandHelper(minArgs: 3, usage: "<group_name> <flags> <immunity>", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
[RequiresPermissions("@css/root")]
public void OnAddGroup(CCSPlayerController? caller, CommandInfo command)
{
if (_database == null) return;

if (!command.GetArg(1).StartsWith("#"))
{
command.ReplyToCommand($"Group name must start with #.");
return;
}

if (!command.GetArg(2).StartsWith("@") && !command.GetArg(2).StartsWith("#"))
{
command.ReplyToCommand($"Invalid flag or group.");
return;
}

string groupName = command.GetArg(1);
string flags = command.GetArg(2);
int immunity = 0;
int.TryParse(command.GetArg(3), out immunity);

AddGroup(caller, groupName, flags, immunity, command);
}

public static void AddGroup(CCSPlayerController? caller, string name, string flags, int immunity, CommandInfo? command = null)
{
if (_database == null) return;
AdminSQLManager _adminManager = new(_database);

List<string> flagsList = flags.Split(',').Select(flag => flag.Trim()).ToList();
_ = _adminManager.AddGroup(name, flagsList, immunity);

if (command != null)
Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer);
Helper.LogCommand(caller, $"css_addgroup {name} {flags} {immunity}");

string msg = $"Created group '{name}' with flags '{flags}'";
if (command != null)
command.ReplyToCommand(msg);
else if (caller != null && caller.IsValid)
caller.PrintToChat(msg);
else
Server.PrintToConsole(msg);
}

[ConsoleCommand("css_delgroup")]
[CommandHelper(minArgs: 1, usage: "<group_name>", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
[RequiresPermissions("@css/root")]
public void OnDelGroupCommand(CCSPlayerController? caller, CommandInfo command)
{
if (_database == null) return;

if (!command.GetArg(1).StartsWith("#"))
{
command.ReplyToCommand($"Group name must start with #.");
return;
}

string groupName = command.GetArg(1);

RemoveGroup(caller, groupName, command);
}

public void RemoveGroup(CCSPlayerController? caller, string name, CommandInfo? command = null)
{
if (_database == null) return;
AdminSQLManager _adminManager = new(_database);
_ = _adminManager.DeleteGroup(name);

AddTimer(2, () =>
{
ReloadAdmins(caller);
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);

if (command != null)
Helper.SendDiscordLogMessage(caller, command, _discordWebhookClientLog, _localizer);
Helper.LogCommand(caller, $"css_delgroup {name}");

string msg = $"Removed group '{name}'";
if (command != null)
command.ReplyToCommand(msg);
else if (caller != null && caller.IsValid)
caller.PrintToChat(msg);
else
Server.PrintToConsole(msg);
}

[ConsoleCommand("css_reloadadmins")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
[RequiresPermissions("@css/root")]
public void OnRelAdminCommand(CCSPlayerController? caller, CommandInfo command)
Expand All @@ -217,7 +307,7 @@ public void OnRelAdminCommand(CCSPlayerController? caller, CommandInfo command)

ReloadAdmins(caller);

command.ReplyToCommand("Reloaded sql admins");
command.ReplyToCommand("Reloaded sql admins and groups");
}

public void ReloadAdmins(CCSPlayerController? caller)
Expand All @@ -234,6 +324,7 @@ public void ReloadAdmins(CCSPlayerController? caller)
}

AdminSQLManager _adminManager = new(_database);
_ = _adminManager.GiveAllGroupsFlags();
_ = _adminManager.GiveAllFlags();
}

Expand Down
4 changes: 3 additions & 1 deletion Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class CustomServerCommandData

[JsonPropertyName("Command")]
public string Command { get; set; } = "";

[JsonPropertyName("ExecuteOnClient")]
public bool ExecuteOnClient { get; set; } = false;
}
Expand Down Expand Up @@ -60,6 +60,8 @@ public class CS2_SimpleAdminConfig : BasePluginConfig

[JsonPropertyName("BanType")]
public int BanType { get; set; } = 1;
[JsonPropertyName("MultiServerMode")]
public bool MultiServerMode { get; set; } = true;

[JsonPropertyName("ExpireOldIpBans")]
public int ExpireOldIpBans { get; set; } = 0;
Expand Down
8 changes: 4 additions & 4 deletions Database/Migrations/001_CreateTables.sql
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,24 @@ CREATE TABLE IF NOT EXISTS `sa_mutes` (
`server_id` INT NULL,
`status` enum('ACTIVE','UNMUTED','EXPIRED','') NOT NULL DEFAULT 'ACTIVE',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `sa_admins` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`player_name` varchar(128) NOT NULL,
`player_steamid` varchar(64) NOT NULL,
`flags` TEXT NOT NULL,
`immunity` varchar(64) NOT NULL DEFAULT '0',
`immunity` int(11) NOT NULL DEFAULT 0,
`server_id` INT NULL,
`ends` timestamp NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `sa_servers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`hostname` varchar(128) NOT NULL,
`address` varchar(64) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `address` (`address`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
26 changes: 26 additions & 0 deletions Database/Migrations/006_ServerGroupsFeature.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
CREATE TABLE IF NOT EXISTS `sa_groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`immunity` int(11) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `sa_groups_flags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) NOT NULL,
`flag` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `sa_groups_servers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`group_id` int(11) NOT NULL,
`server_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

ALTER TABLE `sa_admins` ADD `group_id` INT NULL AFTER `created`;

ALTER TABLE `sa_groups_flags` ADD FOREIGN KEY (`group_id`) REFERENCES `sa_groups`(`id`) ON DELETE CASCADE;
ALTER TABLE `sa_groups_servers` ADD FOREIGN KEY (`group_id`) REFERENCES `sa_groups`(`id`) ON DELETE CASCADE;
ALTER TABLE `sa_admins` ADD FOREIGN KEY (`group_id`) REFERENCES `sa_groups`(`id`) ON DELETE SET NULL;
1 change: 1 addition & 0 deletions Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,7 @@ await connection.ExecuteAsync(
}
}

await _adminManager.GiveAllGroupsFlags();
await _adminManager.GiveAllFlags();
});
}, CounterStrikeSharp.API.Modules.Timers.TimerFlags.STOP_ON_MAPCHANGE);
Expand Down
172 changes: 171 additions & 1 deletion Managers/AdminSQLManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,101 @@ flagObj is not string flag ||
}
}

public async Task<Dictionary<int, Tuple<List<string>, List<Tuple<string, DateTime?>>, int>>> GetAllGroupsFlags()
{
try
{
await using MySqlConnection connection = await _database.GetConnectionAsync();

string sql = "SELECT group_id FROM sa_groups_servers WHERE server_id = @serverid";
var groupIds = connection.Query<int>(sql, new { serverid = CS2_SimpleAdmin.ServerId }).ToList();

sql = @"
SELECT g.group_id, f.flag
FROM sa_groups_flags f
JOIN sa_groups_servers g ON f.group_id = g.group_id
WHERE g.server_id = @serverid";

var groupFlagData = connection.Query(sql, new { serverid = CS2_SimpleAdmin.ServerId }).ToList();

if (groupIds.Count == 0 || groupFlagData.Count == 0)
{
return [];
}

var groupInfoDictionary = new Dictionary<int, Tuple<List<string>, List<Tuple<string, DateTime?>>, int>>();

foreach (var groupId in groupIds)
{
groupInfoDictionary[groupId] = new Tuple<List<string>, List<Tuple<string, DateTime?>>, int>([], [], 0);
}

foreach (var row in groupFlagData)
{
var groupId = (int)row.group_id;
var flag = (string)row.flag;

groupInfoDictionary[groupId].Item1.Add(flag);
}

sql = @"
SELECT a.group_id, a.player_steamid, a.ends, g.immunity
FROM sa_admins a
JOIN sa_groups g ON a.group_id = g.id
WHERE a.group_id IN @groupIds";

var playerData = (await connection.QueryAsync(sql, new { groupIds })).ToList();

foreach (var row in playerData)
{
var groupId = (int)row.group_id;
var playerSteamid = (string)row.player_steamid;
var ends = row.ends as DateTime?;
var immunity = (int)row.immunity;

groupInfoDictionary[groupId].Item2.Add(new Tuple<string, DateTime?>(playerSteamid, ends));
groupInfoDictionary[groupId] = new Tuple<List<string>, List<Tuple<string, DateTime?>>, int>(groupInfoDictionary[groupId].Item1, groupInfoDictionary[groupId].Item2, immunity);
}

return groupInfoDictionary;
}
catch { }

return [];
}



public async Task GiveAllGroupsFlags()
{
Dictionary<int, Tuple<List<string>, List<Tuple<string, DateTime?>>, int>> groupFlags = await GetAllGroupsFlags();

foreach (var kvp in groupFlags)
{
var flags = kvp.Value.Item1;
var players = kvp.Value.Item2;
int immunity = kvp.Value.Item3;

foreach (var playerTuple in players)
{
var steamIdStr = playerTuple.Item1;
var ends = playerTuple.Item2;

if (!string.IsNullOrEmpty(steamIdStr) && SteamID.TryParse(steamIdStr, out var steamId) && steamId != null)
{
if (!_adminCache.ContainsKey(steamId))
{
_adminCache.TryAdd(steamId, ends);
}

Helper.GivePlayerFlags(steamId, flags, (uint)immunity);
// Often need to call 2 times
Helper.GivePlayerFlags(steamId, flags, (uint)immunity);
}
}
}
}

public async Task GiveAllFlags()
{
List<(string, List<string>, int, DateTime?)> allPlayers = await GetAllPlayersFlags();
Expand Down Expand Up @@ -221,7 +316,22 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, Lis
// Insert flags into sa_admins_flags table
foreach (var flag in flagsList)
{
Console.WriteLine(flag);
if (flag.StartsWith("#"))
{
string sql = "SELECT id FROM `sa_groups` WHERE name = @groupName";
int? groupId = await connection.QuerySingleOrDefaultAsync<int?>(sql, new { groupName = flag });

if (groupId != null)
{
var updateAdminGroup = "UPDATE `sa_admins` SET group_id = @groupId WHERE id = @adminId";
await connection.ExecuteAsync(updateAdminGroup, new
{
groupId,
adminId
});
}
}

var insertFlagsSql = "INSERT INTO `sa_admins_flags` (`admin_id`, `flag`) " +
"VALUES (@adminId, @flag)";

Expand All @@ -238,6 +348,66 @@ public async Task AddAdminBySteamId(string playerSteamId, string playerName, Lis
}
}

public async Task AddGroup(string groupName, List<string> flagsList, int immunity = 0)
{
if (string.IsNullOrEmpty(groupName) || flagsList == null || flagsList.Count == 0) return;

try
{
await using MySqlConnection connection = await _database.GetConnectionAsync();

// Insert group into sa_groups table
var insertGroup = "INSERT INTO `sa_groups` (`name`, `immunity`) " +
"VALUES (@groupName, @immunity); SELECT LAST_INSERT_ID();";
int groupId = await connection.ExecuteScalarAsync<int>(insertGroup, new
{
groupName,
immunity
});

// Insert flags into sa_groups_flags table
foreach (var flag in flagsList)
{
var insertFlagsSql = "INSERT INTO `sa_groups_flags` (`group_id`, `flag`) " +
"VALUES (@groupId, @flag)";

await connection.ExecuteAsync(insertFlagsSql, new
{
groupId,
flag
});
}

if (CS2_SimpleAdmin.ServerId != null)
{
string insertGroupServer = "INSERT INTO `sa_groups_servers` (`group_id`, `server_id`) " +
"VALUES (@groupId, @server_id)";
await connection.ExecuteAsync(insertGroupServer, new { groupId, server_id = CS2_SimpleAdmin.ServerId });
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

public async Task DeleteGroup(string groupName)
{
if (string.IsNullOrEmpty(groupName)) return;

try
{
await using MySqlConnection connection = await _database.GetConnectionAsync();

string sql = "DELETE FROM `sa_groups` WHERE name = @groupName";
await connection.ExecuteAsync(sql, new { groupName });
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}

public async Task DeleteOldAdmins()
{
try
Expand Down
Loading

0 comments on commit 1cfff86

Please sign in to comment.