using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Newtonsoft.Json; using Oxide.Core; using Oxide.Core.Plugins; using UnityEngine; namespace Oxide.Plugins { [Info("VoteScript", "VoteRank", "2.1.0")] [Description("Vote rewards with VoteScript. /claimvote or /claimvote CODE")] public class VoteScript : RustPlugin { private class Settings { [JsonProperty("Url")] public string Url = "https://votescript.voterank.net"; [JsonProperty("Api key")] public string Key = ""; // Keys listed here run these console commands instead of giving an item. [JsonProperty("Commands by reward key")] public Dictionary> Commands = new Dictionary> { ["vip_day"] = new List { "oxide.usergroup add {steamid} vip" } }; // Reward types. Anything not allowed here stays waiting in VoteScript; the dashboard sends names and numbers, never commands. [JsonProperty("Most days one claim can give")] public int MaxDays = 365; [JsonProperty("Groups votes may give, for vip/NAME and group/NAME (reward name: Oxide group)")] public Dictionary Groups = new Dictionary { ["vip"] = "vip" }; [JsonProperty("Permissions votes may give, for permission/NAME")] public List Permissions = new List(); [JsonProperty("Places, for teleport/NAME (x, y, z)")] public Dictionary Places = new Dictionary(); [JsonProperty("Seconds after a fight before a teleport")] public float CombatSeconds = 30f; [JsonProperty("Own actions, for run/NAME (console commands; {steamid} and {amount} are filled in)")] public Dictionary> Run = new Dictionary>(); } private class Item { public string key; public string name; public int amount; } private class Answer { public bool ok; public string error; public int votes; public int held; public List items; } // Timed groups that this plugin takes back itself, and references of unfinished claims. private class Stored { public Dictionary Refs = new Dictionary(); public Dictionary Until = new Dictionary(); } [PluginReference] private Plugin TimedPermissions, Economics, ServerRewards; private Settings settings; private readonly HashSet busy = new HashSet(); private Stored stored = new Stored(); private void Init() { try { stored = Interface.Oxide.DataFileSystem.ReadObject("VoteScript") ?? new Stored(); } catch (Exception) { PrintError("The data file is not valid."); } } private void OnServerInitialized() { Expire(); timer.Every(60f, Expire); } private void Keep() { Interface.Oxide.DataFileSystem.WriteObject("VoteScript", stored); } protected override void LoadDefaultConfig() { settings = new Settings(); } protected override void LoadConfig() { base.LoadConfig(); try { settings = Config.ReadObject() ?? new Settings(); } catch { PrintError("The config file is not valid; using defaults."); settings = new Settings(); } SaveConfig(); } protected override void SaveConfig() { Config.WriteObject(settings, true); } [ChatCommand("claimvote")] private void CmdClaim(BasePlayer player, string command, string[] args) { if (!busy.Add(player.userID)) { SendReply(player, "Your votes are already being checked."); return; } string code = args.Length > 0 ? args[0] : null; string slot = player.UserIDString + "|" + code; string reference; // Kept until an answer arrives, so a lost answer cannot lose or double a reward. if (!stored.Refs.TryGetValue(slot, out reference)) { stored.Refs[slot] = reference = "rust-" + Guid.NewGuid().ToString("N"); Keep(); } string body = "player=" + player.UserIDString + "&ref=" + reference + "&types=" + Uri.EscapeDataString(string.Join(",", Types().ToArray())) + (code == null ? "" : "&code=" + Uri.EscapeDataString(code)); var headers = new Dictionary { ["X-Api-Key"] = settings.Key }; webrequest.Enqueue(settings.Url.TrimEnd('/') + "/index.php?r=api/v1/" + (code == null ? "claim" : "claim-code"), body, (status, text) => { busy.Remove(player.userID); Answer answer = null; try { if (status == 200 && text != null) answer = JsonConvert.DeserializeObject(text); } catch (JsonException) { } if (player == null || !player.IsConnected) return; // the next claim repeats this one if (answer == null) { PrintWarning("VoteScript answered " + status); SendReply(player, "Votes cannot be checked right now. Try again in a minute."); return; } string now; if (!stored.Refs.TryGetValue(slot, out now) || now != reference) return; // answered twice if (answer.ok && answer.items.Count > 0 && answer.items.Any(i => i.key.StartsWith("teleport/")) && Fighting(player)) { SendReply(player, "Your vote reward teleports you. Type the command again when you are not fighting, hurt or mounted."); return; // kept for then } stored.Refs.Remove(slot); Keep(); if (!answer.ok) { SendReply(player, answer.error); return; } if (answer.votes == 0 && answer.items.Count == 0) { SendReply(player, 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 (Item item in answer.items.OrderBy(i => i.key.StartsWith("teleport/") ? 1 : 0)) { try { Give(player, item); } catch (Exception e) { PrintError(player.UserIDString + " did not get " + item.key + " x" + item.amount + ": " + e.Message); } } SendReply(player, "Thank you for voting! Rewards for " + answer.votes + " vote(s)."); }, this, Oxide.Core.Libraries.RequestMethod.POST, headers, 15f); } /* ---------------------------------------------- reward types */ private static readonly HashSet Known = new HashSet { "vip", "group", "permission", "title", "teleport", "storage", "until", "unlock", "xp", "boost", "effect", "outfit", "mount", "spell", "badge", "run", "custom" }; private static bool Plain(string key) { int at = key.IndexOf('/'); return at < 0 || !Known.Contains(key.Substring(0, at)); } // Other plugins can give more: hook object OnVoteScriptReward(BasePlayer, string key, int amount), and say so with // hook List OnVoteScriptTypes(), such as "title" or "custom/kit". private List Types() { var list = new List { "item" }; foreach (var g in settings.Groups) { // A dashboard must never be able to make anyone staff. if (g.Value == "admin" || g.Value == "moderator" || !permission.GroupExists(g.Value)) continue; list.Add("vip/" + g.Key); list.Add("group/" + g.Key); } foreach (string p in settings.Permissions) list.Add("permission/" + p); foreach (string p in settings.Places.Keys) list.Add("teleport/" + p); foreach (string r in settings.Run.Keys) list.Add("run/" + r); var more = Interface.CallHook("OnVoteScriptTypes") as List; if (more != null) list.AddRange(more); return list; } private readonly Dictionary fights = new Dictionary(); private void OnEntityTakeDamage(BasePlayer player, HitInfo info) { if (player == null || info == null) return; fights[(ulong)player.userID] = Time.realtimeSinceStartup; BasePlayer by = info.Initiator as BasePlayer; if (by != null && by != player) fights[(ulong)by.userID] = Time.realtimeSinceStartup; } private bool Fighting(BasePlayer player) { float at; if (player.IsDead() || player.IsWounded() || player.isMounted) return true; // Plugins such as NoEscape answer this hook when a player may not teleport now. if (Interface.Oxide.CallHook("CanTeleport", player) != null) return true; return fights.TryGetValue((ulong)player.userID, out at) && Time.realtimeSinceStartup - at < settings.CombatSeconds; } private void Give(BasePlayer player, Item item) { if (item.amount < 1) return; if (Interface.CallHook("OnVoteScriptReward", player, item.key, item.amount) != null) return; if (!Plain(item.key) && Regex.IsMatch(item.key, "^[a-z]+(/[A-Za-z0-9_.:-]{1,40}){1,2}$")) { string[] p = item.key.Split('/'); string id = player.UserIDString, forever = p.Length > 2 ? p[2] : ""; string group; float[] at; List run; int days = Math.Min(item.amount, settings.MaxDays); if ((p[0] == "vip" || p[0] == "group") && settings.Groups.TryGetValue(p[1], out group) && Types().Contains(p[0] + "/" + p[1])) { if (forever == "forever") permission.AddUserGroup(id, group); else if (TimedPermissions != null) Server.Command("addgroup", id, group, days + "d"); else Timed("group", id, group, days); return; } if (p[0] == "permission" && settings.Permissions.Contains(p[1])) { if (forever == "forever") permission.GrantUserPermission(id, p[1], null); else if (TimedPermissions != null) Server.Command("grantperm", id, p[1], days + "d"); else Timed("permission", id, p[1], days); return; } if (p[0] == "teleport" && settings.Places.TryGetValue(p[1], out at) && at.Length == 3) { player.Teleport(new Vector3(at[0], at[1], at[2])); return; } if (p[0] == "run" && settings.Run.TryGetValue(p[1], out run)) { Commands(player, item, run); return; } } if (!Plain(item.key)) { PrintWarning("Nothing here gives " + item.key + "; " + player.UserIDString + " did not get it."); return; } List commands; if (settings.Commands.TryGetValue(item.key, out commands)) { Commands(player, item, commands); return; } if (item.key == "economics" && Economics != null) { Economics.Call("Deposit", (ulong)player.userID, (double)item.amount); return; } if (item.key == "serverrewards" && ServerRewards != null) { ServerRewards.Call("AddPoints", (ulong)player.userID, item.amount); return; } var made = ItemManager.CreateByName(item.key, item.amount); if (made == null) { PrintWarning("No item or command for reward key " + item.key); return; } player.GiveItem(made); } private void Commands(BasePlayer player, Item item, List commands) { foreach (string c in commands) Server.Command(c.Replace("{steamid}", player.UserIDString).Replace("{amount}", item.amount.ToString())); } // Without Timed Permissions: kept here, and taken back when the days are over. private void Timed(string kind, string id, string name, int days) { string key = kind + "|" + id + "|" + name; bool has = kind == "group" ? permission.UserHasGroup(id, name) : permission.UserHasPermission(id, name); if (has && !stored.Until.ContainsKey(key)) { PrintWarning(id + " already has " + name + " for good."); return; } long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(), old; stored.Until.TryGetValue(key, out old); stored.Until[key] = Math.Max(now, old) + days * 86400L; Keep(); if (kind == "group") permission.AddUserGroup(id, name); else permission.GrantUserPermission(id, name, null); } private void Expire() { long now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); foreach (var e in stored.Until.Where(x => x.Value <= now).ToList()) { string[] k = e.Key.Split('|'); if (k[0] == "group") permission.RemoveUserGroup(k[1], k[2]); else permission.RevokeUserPermission(k[1], k[2]); stored.Until.Remove(e.Key); Keep(); } } } }