using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using System.Threading.Tasks; using CounterStrikeSharp.API; using CounterStrikeSharp.API.Core; using CounterStrikeSharp.API.Core.Attributes.Registration; using CounterStrikeSharp.API.Modules.Admin; using CounterStrikeSharp.API.Modules.Commands; using CounterStrikeSharp.API.Modules.Entities; using CounterStrikeSharp.API.Modules.Utils; namespace VoteScriptCS2; public sealed class VoteConfig : BasePluginConfig { [JsonPropertyName("Url")] public string Url { get; set; } = "https://votescript.voterank.net"; [JsonPropertyName("ApiKey")] public string ApiKey { get; set; } = ""; // Server commands per reward key. {steamid}, {userid}, {amount} and {key} are filled in. // For types use the exact key, or the type and /*, with {arg} and {arg2} for the parts after it: "run/party", "title/*". [JsonPropertyName("Commands")] public Dictionary> Commands { get; set; } = new() { ["credits"] = new() { "css_givecredits {steamid} {amount}" } }; // vip/NAME and group/NAME (days): the CounterStrikeSharp group or permission it gives, such as "#css/vip" or "@css/vip". // Kept by this plugin and taken back when the days are over. Never list your staff groups here. [JsonPropertyName("Groups")] public Dictionary Groups { get; set; } = new(); // teleport/NAME on a map: "de_dust2/mid": [x, y, z]. Only while the player is alive. [JsonPropertyName("Places")] public Dictionary Places { get; set; } = new(); [JsonPropertyName("MaxDays")] public int MaxDays { get; set; } = 365; } /// !claimvote or !claimvote CODE. Players are known by their SteamID64. public sealed class VoteScriptCS2 : BasePlugin, IPluginConfig { public override string ModuleName => "VoteScript"; public override string ModuleVersion => "2.1.0"; public override string ModuleAuthor => "VoteRank"; public VoteConfig Config { get; set; } = new(); private sealed record Item(string key, string name, long amount); private sealed record Answer(bool ok, string? error, int votes, List? items, int held = 0); // References of unfinished claims and group times survive a restart. private sealed class Stored { public Dictionary Refs { get; set; } = new(); public Dictionary Until { get; set; } = new(); } private static readonly HashSet Known = new() { "vip", "group", "permission", "title", "teleport", "storage", "until", "unlock", "xp", "boost", "effect", "outfit", "mount", "spell", "badge", "run", "custom" }; private Stored stored = new(); private string DataFile => Path.Combine(ModuleDirectory, "votescript-data.json"); public override void Load(bool hotReload) { try { if (File.Exists(DataFile)) stored = JsonSerializer.Deserialize(File.ReadAllText(DataFile)) ?? new(); } catch (Exception e) { Console.WriteLine("[VoteScript] " + DataFile + ": " + e.Message); } RegisterListener((slot, id) => Server.NextFrame(() => Groups(id.SteamId64))); AddTimer(60f, () => { foreach (var p in Utilities.GetPlayers()) if (!p.IsBot) Groups(p.SteamID); }, CounterStrikeSharp.API.Modules.Timers.TimerFlags.REPEAT); } private void Keep() { try { File.WriteAllText(DataFile + ".tmp", JsonSerializer.Serialize(stored)); File.Move(DataFile + ".tmp", DataFile, true); } catch (Exception e) { Console.WriteLine("[VoteScript] cannot save: " + e.Message); } } private static readonly HttpClient Http = new(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(10) }; private readonly ConcurrentDictionary busy = new(); public void OnConfigParsed(VoteConfig config) => Config = config; [ConsoleCommand("css_claimvote", "Claim your vote rewards")] [CommandHelper(whoCanExecute: CommandUsage.CLIENT_ONLY)] public void OnClaim(CCSPlayerController? player, CommandInfo command) { if (player == null || !player.IsValid) return; ulong id = player.SteamID; if (!busy.TryAdd(id, true)) { player.PrintToChat("Your votes are already being checked."); return; } string? code = command.ArgCount > 1 ? command.GetArg(1) : null; string slot = id + "|" + code; // Kept until an answer arrives, so a lost answer cannot lose or double a reward. if (!stored.Refs.TryGetValue(slot, out string? reference)) { stored.Refs[slot] = reference = "cs2-" + Guid.NewGuid().ToString("N"); Keep(); } string types = string.Join(",", Types()); int userId = player.UserId ?? -1; Task.Run(async () => { Answer? answer = null; try { var form = new Dictionary { ["player"] = id.ToString(), ["ref"] = reference, ["types"] = types }; if (code != null) form["code"] = code; using var request = new HttpRequestMessage(HttpMethod.Post, Config.Url.TrimEnd('/') + "/index.php?r=api/v1/" + (code == null ? "claim" : "claim-code")) { Content = new FormUrlEncodedContent(form) }; request.Headers.Add("X-Api-Key", Config.ApiKey); using var response = await Http.SendAsync(request); if (response.IsSuccessStatusCode) answer = JsonSerializer.Deserialize(await response.Content.ReadAsStringAsync()); else Console.WriteLine("[VoteScript] answer " + (int)response.StatusCode); } catch (Exception e) { Console.WriteLine("[VoteScript] " + e.Message); } Server.NextFrame(() => Finish(id, userId, slot, reference, answer)); }); } private void Finish(ulong id, int userId, string slot, string reference, Answer? answer) { busy.TryRemove(id, out _); var player = Utilities.GetPlayerFromSteamId(id); if (player == null || !player.IsValid) return; // left: the next claim repeats this one if (answer == null) { player.PrintToChat("Votes cannot be checked right now. Try again in a minute."); return; } if (!stored.Refs.TryGetValue(slot, out var now) || now != reference) return; // answered twice var items = answer.items ?? new(); if (answer.ok && items.Any(i => Kind(i.key) == "teleport") && !player.PawnIsAlive) { player.PrintToChat("Your vote reward teleports you. Type the command again when you are alive."); return; // kept for then } stored.Refs.Remove(slot); Keep(); if (!answer.ok) { player.PrintToChat(answer.error ?? "This code cannot be used."); return; } if (answer.votes == 0 && items.Count == 0) { player.PrintToChat(answer.held > 0 ? "Your vote reward cannot be given on this server yet. It stays waiting." : "You have no votes to claim."); return; } // Teleports after everything else. One that fails does not stop, or repeat, the others. foreach (var item in items.OrderBy(i => Kind(i.key) == "teleport" ? 1 : 0)) { try { Give(player, id, userId, item); } catch (Exception e) { Console.WriteLine($"[VoteScript] {id} did not get {item.key} x{item.amount}: {e.Message}"); } } player.PrintToChat($"Thank you for voting! Rewards for {answer.votes} vote(s)."); } /* ------------------------------------------------ reward types */ private static string Kind(string key) { int at = key.IndexOf('/'); return at > 0 && Known.Contains(key[..at]) ? key[..at] : "item"; } // "@css/root" and other staff permissions can never come from a dashboard. private static bool Harmless(string group) => Regex.IsMatch(group, "^[#@][A-Za-z0-9_]+/[A-Za-z0-9_-]+$") && !Regex.IsMatch(group, "/(root|admin|rcon|cheats|config|ban|kick|unban|slay|generic|superadmin)$", RegexOptions.IgnoreCase); private static string? Place(string key) => Regex.IsMatch(key, "^teleport/[A-Za-z0-9_-]{1,40}$") ? Server.MapName + "/" + key[9..] : null; private List Types() { var list = new List(); foreach (var k in Config.Commands.Keys) { if (Kind(k) == "item") { if (!list.Contains("item")) list.Add("item"); } else if (!k.EndsWith("/*")) list.Add(k); else if (Kind(k) is not ("group" or "permission" or "spell")) list.Add(k[..^2]); } foreach (var g in Config.Groups) if (Harmless(g.Value)) { list.Add("vip/" + g.Key); list.Add("group/" + g.Key); } // Places on other maps count too: the reward waits for the next claim there. foreach (var p in Config.Places.Keys) if (p.StartsWith(Server.MapName + "/")) list.Add("teleport/" + p[(Server.MapName.Length + 1)..]); return list; } private void Give(CCSPlayerController player, ulong id, int userId, Item item) { if (item.amount < 1 || !Regex.IsMatch(item.key, "^[A-Za-z0-9_.:,/-]{1,100}$")) { Console.WriteLine("[VoteScript] refused reward key " + item.key); return; } string kind = Kind(item.key); string[] a = item.key.Split('/'); if (kind is "vip" or "group" && a.Length == 2 && Config.Groups.TryGetValue(a[1], out var group) && Harmless(group)) { string k = id + "|" + a[1]; long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); stored.Until[k] = Math.Max(now, stored.Until.GetValueOrDefault(k)) + Math.Min(item.amount, Config.MaxDays) * 86400; Keep(); Groups(id); return; } if (kind == "teleport" && Place(item.key) is string place && Config.Places.TryGetValue(place, out var at) && at.Length == 3) { player.PlayerPawn.Value!.Teleport(new Vector(at[0], at[1], at[2]), null, new Vector(0, 0, 0)); return; } if (!Config.Commands.TryGetValue(item.key, out var commands) && !(kind is not ("item" or "group" or "permission" or "spell") && Config.Commands.TryGetValue(kind + "/*", out commands))) { Console.WriteLine($"[VoteScript] nothing here gives {item.key}; {id} did not get it"); return; } string arg = kind == "item" ? "" : a[1], arg2 = kind != "item" && a.Length > 2 ? a[2] : ""; long amount = kind is "vip" or "group" or "permission" or "title" or "unlock" or "until" ? Math.Min(item.amount, Config.MaxDays) : item.amount; foreach (var c in commands!) Server.ExecuteCommand(c.Replace("{steamid}", id.ToString()).Replace("{userid}", "#" + userId).Replace("{amount}", amount.ToString()).Replace("{key}", item.key).Replace("{arg2}", arg2).Replace("{arg}", arg)); } // Admin data lives in memory, so it is given again when the player joins. private void Groups(ulong id) { var steam = new SteamID(id); long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); foreach (var g in Config.Groups) { string k = id + "|" + g.Key; if (!stored.Until.TryGetValue(k, out long until) || !Harmless(g.Value)) continue; if (until > now) { if (g.Value[0] == '#') AdminManager.AddPlayerToGroup(steam, g.Value); else AdminManager.AddPlayerPermissions(steam, g.Value); continue; } if (g.Value[0] == '#') AdminManager.RemovePlayerFromGroup(steam, true, g.Value); else AdminManager.RemovePlayerPermissions(steam, g.Value); stored.Until.Remove(k); Keep(); } } }