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

FREE RaidProtection : 3.2.1 3.2.1

Нет прав для скачивания
C#:
using Oxide.Core.Libraries.Covalence;
using Newtonsoft.Json;
using Oxide.Core;
using System.Collections.Generic;
using Oxide.Core.Plugins;
using System.Linq;
using System.Text;
using Oxide.Game.Rust.Cui;
using UnityEngine;
using Oxide.Plugins;
using System;
namespace Oxide.Plugins {
    [Info("RaidProtection", "mr01sam", "3.2.1")]
    [Description("Provides raid protection to bases at the cost of a resource.")]
    partial class RaidProtection : CovalencePlugin {
        public static RaidProtection 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;
        private bool PluginLoaded = true;
        private bool ShowConfigWarnings = true;
        public const string PermissionAdmin = "raidprotection.admin";
        public readonly string PermissionLevel = "raidprotection.level.";
        private void OnServerInitialized() {
            PLUGIN = this;
            DependencyCheck();
            if (!PluginLoaded) {
                return;
            }
            if (!permission.PermissionExists(PermissionAdmin, this)) {
                permission.RegisterPermission(PermissionAdmin, this);
            }
            AddCovalenceCommand(config.Commands.Admin, nameof(CmdController));
            AddCovalenceCommand(config.Commands.Levels, nameof(UILevelsShow));
            AddCovalenceCommand(config.Commands.Protection, nameof(TcInfoShowPlayer));
            InitProtectionLevels();
            LoadImages();
            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();
            }
            );
        }
        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(OnActiveItemChanged));
            Unsubscribe(nameof(OnPlayerDeath));
        }
        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(OnActiveItemChanged));
            Subscribe(nameof(OnPlayerDeath));
        }
        private void Unload() {
            if (PLUGIN != null) {
                UnloadIntegrations();
            }
            SaveProtectedCupboards();
            if (config.EnableLedger) {
                BalanceLedger.SaveAll();
            }
            UnsubscribePlugins();
        }
        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.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) {
                    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);
        }
        private void FindNewCupboards() {
            NextTick(() => {
                var privs = BaseNetworkable.FindObjectsOfType<BuildingPrivlidge>().Where(x => x != null && x.net != null && !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}/{privs.Count} new cupboards");
                    }
                }
            }
            );
        }
        private void LoadProtectedCupboards() {
            NextTick(() => {
                var existing = new Dictionary<string, ProtectedCupboard>();
                try {
                    existing = LoadDataFile<Dictionary<string, ProtectedCupboard>>("ProtectedCupboards");
                    if (existing != null) {
                        int count = 0;
                        int skipped = 0;
                        foreach (var kvp in existing) {
                            try {
                                var priv = kvp.Value.BuildingPrivlidge;
                                var tc = kvp.Value;
                                if (priv != null) {
                                    if (AddProtectedCupboard(priv, tc)) {
                                        count++;
                                    }
                                }
                            }
                            catch (Exception) {
                                skipped++;
                            }
                        }
                        var totalCount = existing.Count - skipped;
                        if (totalCount > 0 && totalCount >= count && config.EnableConsoleMessages) {
                            Puts($"Loaded {count}/{totalCount} existing cupboards");
                        }
                    }
                }
                catch (Exception) {
                    PrintError("Failed to load protected cupboards");
                }
            }
            );
        }
        private void SaveProtectedCupboards() {
            try {
                var allCupboards = ProtectedCupboardManager._protectedCupboards;
                SaveDataFile("ProtectedCupboards", allCupboards);
                if (config.EnableConsoleMessages) {
                    Puts($"Saved {allCupboards.Count} cupboards");
                }
            }
            catch {
                PrintError("Failed to save protected cupboards");
            }
        }
    }
}
namespace Oxide.Plugins {
    partial class RaidProtection {
        /*
         * 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<BasePlayer> GetOwners(BaseEntity entity) {
            var retVal = new List<BasePlayer>();
            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 BasePlayer GetFounder(BaseEntity entity) {
            BasePlayer 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;
        }
    }
}
namespace Oxide.Plugins {
    partial class RaidProtection {
        private readonly string[] CHANGELOG = new string[] {
            "Fixed issue where offline timers wouldn't get properly reset when damage was taken", "Added 'tc offline' command, used for debugging purposes"
        }
        ;
    }
}
namespace Oxide.Plugins {
    partial class RaidProtection {
        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(ProtectedCupboard 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(ProtectedCupboard tc) {
                if (_activeTimers.ContainsKey(tc.ID)) {
                    var timer = _activeTimers[tc.ID];
                    timer.Destroy();
                    _activeTimers.Remove(tc.ID);
                }
            }
        }
    }
}
namespace Oxide.Plugins {
    partial class RaidProtection : 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 RaidProtection {
#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();
            }
        }
        ;
#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 = "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, "command player not found", "<not given>");
                return null;
            }
            BasePlayer basePlayer = caller;
            if (args.Length >= length) {
                basePlayer = BasePlayer.FindAwakeOrSleeping(args[index]);
            }
            return basePlayer;
        }
        private BuildingPrivlidge GetPrivFromId(string id) {
            return ProtectedCupboardManager.GetByID(ulong.Parse(id)).BuildingPrivlidge;
        }
        private ProtectedCupboard GetTcFromId(string id) {
            return ProtectedCupboardManager.GetByID(ulong.Parse(id));
        }
        private ProtectedCupboard GetTcFromIdOrPlayer(IPlayer player, string command, string[] args, int indexOfTcId = 0, int totalExpectedLengthOfArgs = 1) {
            BasePlayer caller = player.Object as BasePlayer;
            if (player.IsServer && args.Length < totalExpectedLengthOfArgs) {
                Message(caller, "command invalid value", args[0]);
                return null;
            }
            else if (args.Length < totalExpectedLengthOfArgs) {
                var priv = caller.GetBuildingPrivilege();
                if (priv == null) {
                    return null;
                }
                return ProtectedCupboardManager.GetByID(priv.net.ID.Value);
            }
            var id = ulong.Parse(args[indexOfTcId]);
            return ProtectedCupboardManager.GetByID(id);
        }
#endregion
#region Controller
        private void CmdController(IPlayer player, string command, string[] args) {
            try {
                if (args.Length == 0) {
                    args = new string[] {
                        "help"
                    }
                    ;
                }
                CommandInfo commandInfo = null;
                if (args.Length >= 2) {
                    commandInfo = Commands.OrderByDescending(x => x.CommandWordCount).FirstOrDefault(x => x.Command == string.Join(" ", new[] {
                        args[0], args[1]
                    }
                    ));
                }
                if (commandInfo == null) {
                    commandInfo = Commands.FirstOrDefault(x => x.Command == args[0]);
                }
                if (commandInfo == null) {
                    CmdHelp(player, command, args);
                    return;
                }
                // Permission
                if (!player.IsServer) {
                    foreach (var perm in commandInfo.Permissions) {
                        if (!permission.UserHasPermission(player.Id, perm)) {
                            Message(player.Object as BasePlayer, "command no permission", perm);
                            return;
                        }
                    }
                }
                args = args.Skip(commandInfo.CommandWordCount).ToArray();
                // Validation
                var resp = commandInfo.Validate(player.IsServer, args);
                if (resp.IsValid) {
                    if (player.IsServer && args.Length < commandInfo.TotalArgCount) {
                        Message(player.Object as BasePlayer, "command all args required");
                        Message(player.Object as BasePlayer, "command usage", config.Commands.Admin, commandInfo.Command, commandInfo.ArgString);
                        return;
                    }
                    commandInfo.Execute(player, command, args);
                }
                else {
                    var message = Lang("command usage", player.Object as BasePlayer, config.Commands.Admin, commandInfo.Command, commandInfo.ArgString);
                    switch (resp.StatusCode) {
                        case ValidationStatusCode.PLAYER_NOT_FOUND : message = Lang("command player not found", player.Id, resp.Data);
                        break;
                        case ValidationStatusCode.INVALID_VALUE : case ValidationStatusCode.VALUE_NOT_ALLOWED : message = Lang("command invalid value", player.Id, resp.Data);
                        break;
                    }
                    MessageNonLocalized(player.Object as BasePlayer, message);
                }
            }
            catch (Exception) {
                Message(player.Object as BasePlayer, "command error");
            }
        }
#endregion
#region Methods
        private void CmdHelp(IPlayer player, string command, string[] args) {
            if (player.IsServer) {
                Puts("\n" + string.Join("\n", Commands.Select(x => $"{config.Commands.Admin} {x.Command} {x.ArgString}".PadRight(60) + x.Description)));
            }
            else {
                ShowHelp(player.Object as BasePlayer);
            }
        }
        private void CmdTcId(IPlayer player, string command, string[] args) {
            var basePlayer = GetPlayerOrTarget(player, command, args);
            if (basePlayer == null) {
                return;
            }
            var priv = basePlayer.GetBuildingPrivilege();
            if (priv == null) {
                Message(player.Object as BasePlayer, "command no tc", basePlayer.displayName);
            }
            else {
                Message(player.Object as BasePlayer, "command id", priv.net.ID);
            }
        }
        private void CmdTcTp(IPlayer player, string command, string[] args) {
            var priv = GetPrivFromId(args[0]);
            var basePlayer = GetPlayerOrTarget(player, command, args, 1, 2);
            basePlayer.MovePosition(priv.transform.position);
            Message(player.Object as BasePlayer, "command success", priv.net.ID);
        }
        private void CmdTcOffline(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            tc.ForceOffline = bool.Parse(args.Last());
            UpdateOnlineOwners(tc);
            Message(player.Object as BasePlayer, "command success", tc.ID, string.Join("\n", tc.Owners.Select(x => x.ToString())));
            Message(player.Object as BasePlayer, "command status", tc.ID, tc.Status, tc.ReasonAndTimeRemaining);
        }
        private void CmdTcOwners(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 1);
            Message(player.Object as BasePlayer, "command owners", tc.ID, string.Join("\n", tc.Owners.Select(x => x.ToString())));
        }
        private void CmdTcOwnersAdd(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            var basePlayer = BasePlayer.FindAwakeOrSleeping(args.Last());
            if (!tc.OwnerUserIds.Contains(basePlayer.userID)) {
                tc.OwnerUserIds.Add(basePlayer.userID);
                UpdateOwners(tc);
            }
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command owners", tc.ID, tc.Owners.ToSentence());
        }
        private void CmdTcOwnersRemove(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            var basePlayer = BasePlayer.FindAwakeOrSleeping(args.Last());
            if (tc.BuildingPrivlidge.IsAuthed(basePlayer)) {
                Message(player.Object as BasePlayer, "command cannot remove auth");
                return;
            }
            if (tc.OwnerUserIds.Contains(basePlayer.userID)) {
                tc.OwnerUserIds.Remove(basePlayer.userID);
                UpdateOwners(tc);
            }
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command owners", tc.ID, tc.Owners.ToSentence());
        }
        private void CmdTcFounder(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args);
            Message(player.Object as BasePlayer, "command founder", tc.ID, tc.FounderDisplayName, tc.HighestProtectionLevel.Rank);
        }
        private void CmdTcFounderSet(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            var basePlayer = BasePlayer.FindAwakeOrSleeping(args.Last());
            tc.SetEntityOwner(basePlayer);
            UpdateOwners(tc);
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command founder", tc.ID, tc.FounderDisplayName, tc.HighestProtectionLevel.Rank);
        }
        private void CmdTcFounderRemove(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args);
            tc.SetEntityOwner(null);
            UpdateOwners(tc);
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command founder", tc.ID, tc.FounderDisplayName, tc.HighestProtectionLevel.Rank);
        }
        private void CmdTcProtection(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args);
            Message(player.Object as BasePlayer, "command protection", tc.ID, tc.CurrentProtectionPercent, tc.OnlineProtectionPercent, tc.OfflineProtectionPercent, tc.HighestProtectionLevel.Rank);
        }
        private void CmdTcCost(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args);
            Message(player.Object as BasePlayer, "command cost", tc.ID, tc.BaseCostPerHour, tc.OwnerCostPerHour, tc.Owners.Count, tc.BuildingCostPerHour, tc.FoundationCount, FormatCurrency(tc.TotalProtectionCostPerHour));
        }
        private void CmdTcBalance(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args);
            Message(player.Object as BasePlayer, "command balance", tc.ID, FormatCurrency(tc.Balance));
        }
        private void CmdTcBalanceSet(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            var amt = float.Parse(args.Last());
            if (tc.Balance <= 0 && tc.Enabled && amt > 0) {
                tc.SkipNextProtectionStartDelay = true;
            }
            ClearProtectionBalance(tc, false);
            UpdateProtectionBalance(tc, float.Parse(args.Last()), BalanceLedgerReason.Command);
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command balance", tc.ID, FormatCurrency(tc.Balance));
        }
        private void CmdTcBalanceAdd(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            var amt = float.Parse(args.Last());
            if (tc.Balance <= 0 && tc.Enabled && amt > 0) {
                tc.SkipNextProtectionStartDelay = true;
            }
            UpdateProtectionBalance(tc, amt, BalanceLedgerReason.Command);
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command balance", tc.ID, FormatCurrency(tc.Balance));
        }
        private void CmdTcBalanceRemove(IPlayer player, string command, string[] args) {
            var tc = GetTcFromIdOrPlayer(player, command, args, 0, 2);
            UpdateProtectionBalance(tc, -float.Parse(args.Last()), BalanceLedgerReason.Command);
            Message(player.Object as BasePlayer, "command success");
            Message(player.Object as BasePlayer, "command balance", 
// ... [Code preview truncated due to length. Full source in attached file] ...

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