cs2-SimpleAdmin/CS2-SimpleAdmin/Managers/ServerManager.cs
Ravid-A 530f60366d Fix unban delay, admin loading, rename persistence; add css_history (1.9.0)
Fixes for issues reported by server owners, plus one new command.

Unbans took up to a minute to apply, and on SQLite never applied at all:
- css_unban only wrote to the database, but the connect check reads an
  in-memory cache that syncs on a 61s timer. BanManager.UnbanPlayer now
  marks the bans UNBANNED in CacheManager and rebuilds the indexes, and
  logs failures instead of swallowing them.
- SQLite has no ON UPDATE CURRENT_TIMESTAMP and the unban/expire queries
  never set updated_at, so the delta refresh never saw the change and
  the ban stayed active until a plugin reload. Both queries set it now.
- The delta query uses >= so a change written in the same second as the
  refresh snapshot is not skipped.
- css_unban issues removeid when UnlockedCommands is on, clearing the
  engine-level banid that css_ban adds.
- RebuildIndexes builds fresh dictionaries and swaps them under a lock,
  so the game thread cannot read a half-built index now that unbans can
  trigger a rebuild off the timer thread.

Admin permissions were intermittently missing after a restart:
- The startup reload fired at a fixed 3s, usually before ServerManager
  had resolved ServerId, so the admin query ran with a null server and
  returned only global admins, with nothing reloading afterwards.
  ServerManager now reloads admins once ServerId is set, and on both of
  its failure paths so global admins still load.
- Loading the plugin mid-map (css_plugins load) fires no map start, so
  server loading is kicked off after 5s if it has not happened.
- CreateAdminsJsonFile no longer strips permissions from inside the
  ToDictionary lambda, where it ran once per name group and seconds
  before the new data was loaded. It returns the new cache and
  PermissionManager.ApplyAdminCache applies it on the main thread
  immediately before AdminManager.LoadAdminData.
- Reloads are serialized with a semaphore and carry a generation, so
  overlapping ones cannot race on the JSON files or apply a stale
  snapshot after the hibernation cap.
- GetAllPlayersFlags and GetAllGroupsData rethrow instead of returning
  an empty list; ReloadAdmins catches, logs and aborts. A transient
  database error previously wrote an empty admins.json and stripped
  every admin on the server.

Permanent renames did not survive a restart:
- New sa_renames table (migration 017); css_prename upserts or deletes,
  and the table is loaded into memory once the server is ready.
- The rename is re-applied on connect before the DatabaseProvider /
  CacheManager early return, which previously skipped it whenever the
  DB or cache was not ready yet.
- New EventPlayerChangename handler, and both it and OnPlayerInfo
  re-check after a short delay instead of comparing names at event
  time; the engine may not have written the client's new name yet, and
  Rename itself takes 0.4s to settle.

Smaller fixes:
- css_say printed "ADMIN: <text>" with no name. The caller name is
  passed to the localizer and sa_adminsay_prefix carries {1} in all 13
  languages.
- css_penalties <player> with @css/kick reassigned only the local user
  id while every lookup kept using caller.SteamID, so an admin checking
  another player always saw their own penalties. It now uses the
  target's SteamID, and replies instead of throwing when that player's
  connect data has not finished loading.
- css_rename returned early for an admin in silent mode, which skipped
  the rename itself rather than just the announcement.

New: css_history <#userid|name|steamid64> [bans|gags|mutes|silences|warns]
(@css/kick) prints every ban, gag, mute, silence and warn with status,
duration, the admin who issued it, the reason and, for lifted bans and
mutes, who lifted it, when and why. A SteamID64 works for players who
are not online. Also available in the admin menu under Players >
History. The data was always there: unban, unmute and expiry only flip
the status column, rows are never deleted.

Build:
- The csproj listed all 32 migration files by hand, so a new migration
  silently never reached the output. Replaced with a glob.
- Commands missing from an existing Commands.json are registered under
  their default name, so new commands appear without deleting the file.
  An empty alias list still disables a command.
2026-10-03 02:33:10 +03:00

146 lines
No EOL
6.2 KiB
C#

using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Modules.Cvars;
using Dapper;
using Microsoft.Extensions.Logging;
namespace CS2_SimpleAdmin.Managers;
public class ServerManager
{
private int _getIpTryCount;
/// <summary>
/// Checks whether the server setting <c>sv_hibernate_when_empty</c> is enabled.
/// Logs an error if this setting is true, since it prevents the plugin from working properly.
/// </summary>
public static void CheckHibernationStatus()
{
var convar = ConVar.Find("sv_hibernate_when_empty");
if (convar == null || !convar.GetPrimitiveValue<bool>())
return;
CS2_SimpleAdmin._logger?.LogError("Detected setting \"sv_hibernate_when_empty true\", set false to make plugin work properly");
}
/// <summary>
/// Initiates the asynchronous process to load server data such as IP address, port, hostname, and RCON password.
/// Handles retry attempts if IP address is not immediately available.
/// Updates or inserts the server record in the database accordingly.
/// After loading, triggers admin reload and cache initialization.
/// Also optionally sends plugin usage metrics if enabled in configuration.
/// </summary>
public void LoadServerData()
{
CS2_SimpleAdmin.Instance.AddTimer(1.0f, () =>
{
if (CS2_SimpleAdmin.ServerLoaded || CS2_SimpleAdmin.DatabaseProvider == null) return;
// Optimization: Get server IP once and reuse
var serverIp = Helper.GetServerIp();
var isInvalidIp = string.IsNullOrEmpty(serverIp) || serverIp.StartsWith("0.0.0");
// Check if we've exceeded retry limit with invalid IP
if (_getIpTryCount > 32 && isInvalidIp)
{
CS2_SimpleAdmin._logger?.LogError("Unable to load server data - can't fetch ip address!");
CS2_SimpleAdmin.Instance.ReloadAdmins(null); // still load global admins
_ = CS2_SimpleAdmin.PlayerManager.LoadRenamedPlayers();
return;
}
// Optimization: Cache ConVar lookups
var ipConVar = ConVar.Find("ip");
var ipAddress = ipConVar?.StringValue;
// Use Helper IP if ConVar IP is invalid
if (string.IsNullOrEmpty(ipAddress) || ipAddress.StartsWith("0.0.0"))
{
ipAddress = serverIp;
// Retry if still invalid and under retry limit
if (_getIpTryCount <= 32 && isInvalidIp)
{
_getIpTryCount++;
LoadServerData();
return;
}
}
// Optimization: Cache remaining ConVar lookups
var hostportConVar = ConVar.Find("hostport");
var hostnameConVar = ConVar.Find("hostname");
var rconPasswordConVar = ConVar.Find("rcon_password");
var address = $"{ipAddress}:{hostportConVar?.GetPrimitiveValue<int>()}";
var hostname = hostnameConVar?.StringValue ?? CS2_SimpleAdmin._localizer?["sa_unknown"] ?? "Unknown";
var rconPassword = rconPasswordConVar?.StringValue ?? "";
CS2_SimpleAdmin.IpAddress = address;
Task.Run(async () =>
{
try
{
await using var connection = await CS2_SimpleAdmin.DatabaseProvider.CreateConnectionAsync();
int? serverId = await connection.ExecuteScalarAsync<int?>(
"SELECT id FROM sa_servers WHERE address = @address",
new { address });
if (serverId == null)
{
await connection.ExecuteAsync(
"INSERT INTO sa_servers (address, hostname, rcon_password) VALUES (@address, @hostname, @rconPassword)",
new { address, hostname, rconPassword });
serverId = await connection.ExecuteScalarAsync<int>(
"SELECT id FROM sa_servers WHERE address = @address",
new { address });
}
else
{
await connection.ExecuteAsync(
"UPDATE sa_servers SET hostname = @hostname, rcon_password = @rconPassword WHERE address = @address",
new { address, hostname, rconPassword });
}
CS2_SimpleAdmin.ServerId = serverId;
CS2_SimpleAdmin._logger?.LogInformation("Loaded server with ip {ip}", ipAddress);
CS2_SimpleAdmin.ServerLoaded = true;
if (CS2_SimpleAdmin.Instance.CacheManager != null)
{
await CS2_SimpleAdmin.Instance.CacheManager.InitializeCacheAsync();
}
// Admins are loaded only now, once ServerId is known, so server-specific admins are included
CS2_SimpleAdmin.Instance.ReloadAdmins(null);
}
catch (Exception ex)
{
CS2_SimpleAdmin._logger?.LogCritical("Unable to create or get server_id: " + ex.Message);
CS2_SimpleAdmin.Instance.ReloadAdmins(null); // still load global admins
}
// Renames are server-independent, so load them even when the server row could not be resolved
await CS2_SimpleAdmin.PlayerManager.LoadRenamedPlayers();
if (CS2_SimpleAdmin.Instance.Config.EnableMetrics)
{
var queryString = $"?address={address}&hostname={hostname}";
var client = CS2_SimpleAdmin.HttpClient;
try
{
await client.GetAsync($"https://api.daffyy.dev/index.php{queryString}");
}
catch (HttpRequestException ex)
{
CS2_SimpleAdmin._logger?.LogWarning($"Unable to make metrics call: {ex.Message}");
}
}
});
CS2_SimpleAdmin.SimpleAdminApi?.OnSimpleAdminReadyEvent();
});
}
}