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

FREE SkinBox : 1.16.3 1.16.3

Нет прав для скачивания
C#:
using System;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using UnityEngine;
using Steamworks;
using Oxide.Core;
using Oxide.Core.Libraries;
using Oxide.Core.Plugins;
using Newtonsoft.Json;
using Oxide.Game.Rust.Cui;

namespace Oxide.Plugins
{
    [Info("SkinBox", "FuJiCuRa", "1.16.3", ResourceId = 17)]
    [Description("SkinBox is a plugin to convert any skinnable item into each skin variant")]
    internal class SkinBox : RustPlugin
    {
        [PluginReference] private Plugin QuickSort, ServerRewards, Economics, StacksExtended;
        private bool skinsLoaded;
        private bool Initialized;
        private bool Changed;
        private static SkinBox skinBox = null;
        private bool activeServerRewards;
        private bool activeEconomics;
        private bool activePointSystem;
        private int maxItemsShown;
        private bool _stacksExtendedExtrasDisabled;
        private Dictionary<string, LinkedList<ulong>> skinsCache = new Dictionary<string, LinkedList<ulong>>();
        private Dictionary<string, LinkedList<ulong>> skinsCacheLimited = new Dictionary<string, LinkedList<ulong>>();
        private Dictionary<string, int> approvedSkinsCount = new Dictionary<string, int>();
        private Dictionary<string, DateTime> cooldownTimes = new Dictionary<string, DateTime>();
        private Dictionary<string, string> NameToItemName = new Dictionary<string, string>();
        private Dictionary<string, string> ItemNameToName = new Dictionary<string, string>();
        private Dictionary<string, object> manualAddedSkinsPre = new Dictionary<string, object>();
        private Dictionary<string, List<ulong>> manualAddedSkins = new Dictionary<string, List<ulong>>();
        private List<ulong> excludedSkins = new List<ulong>();
        private List<object> excludedSkinsPre = new List<object>();
        private Dictionary<ulong, SBH> activeSkinBoxes = new Dictionary<ulong, SBH>();
        private Dictionary<ulong, string> skinWorkshopNames = new Dictionary<ulong, string>();
        private List<object> altSkinBoxCommand;
        private string skinBoxCommand;
        private string permissionUse;
        private bool showLoadedSkinCounts;
        private int exludedSkinsAuthLevel;
        private bool hideQuickSort;
        private string steamApiKey;
        private int accessOverrideAuthLevel;
        private bool allowStackedItems;
        private bool enableCustomPerms;
        private string permCustomPlayerwearable;
        private string permCustomWeapon;
        private string permCustomDeployable;
        private bool useInbuiltSkins;
        private bool useApprovedSkins;
        private int approvedSkinsLimit;
        private bool useManualAddedSkins;
        private int maxPagesShown;
        private bool enableCooldown;
        private int cooldownBox;
        private bool cooldownOverrideAdmin;
        private int cooldownOverrideAuthLevel;
        private bool activateAfterSkinTaken;
        private bool enableUsageCost;
        private bool useServerRewards;
        private bool useEconomics;
        private int costBoxOpen;
        private int costWeapon;
        private int costPlayerwearable;
        private int costDeployable;
        private bool costExcludeAdmins;
        private string costExcludePerm;
        private bool costExcludePermEnabled;

        private object GetConfig(string menu, string datavalue, object defaultValue)
        {
            Dictionary<string, object> data = Config[menu] as Dictionary<string, object>;
            if (data == null)
            {
                data = new Dictionary<string, object>();
                Config[menu] = data;
                Changed = true;
            }

            object value;
            if (!data.TryGetValue(datavalue, out value))
            {
                value = defaultValue;
                data[datavalue] = value;
                Changed = true;
            }

            return value;
        }

        private object getSkincache()
        {
            if (skinsLoaded) return new Dictionary<string, LinkedList<ulong>>(skinsCache);
            else return false;
        }

        private void LoadVariables()
        {
            useInbuiltSkins = Convert.ToBoolean(GetConfig("AvailableSkins", "useInbuiltSkins", true));
            useApprovedSkins = Convert.ToBoolean(GetConfig("AvailableSkins", "useApprovedSkins", false));
            approvedSkinsLimit = Convert.ToInt32(GetConfig("AvailableSkins", "approvedSkinsLimit", -1));
            useManualAddedSkins = Convert.ToBoolean(GetConfig("AvailableSkins", "useManualAddedSkins", true));
            maxPagesShown = Convert.ToInt32(GetConfig("AvailableSkins", "maxPagesShown", 2));
            skinBoxCommand = Convert.ToString(GetConfig("Settings", "skinBoxCommand", "skinbox"));
            altSkinBoxCommand = (List<object>)GetConfig("Settings", "altSkinBoxCommands", new List<object>());
            permissionUse = Convert.ToString(GetConfig("Settings", "permissionUse", "skinbox.use"));
            showLoadedSkinCounts = Convert.ToBoolean(GetConfig("Settings", "showLoadedSkinCounts", true));
            exludedSkinsAuthLevel = Convert.ToInt32(GetConfig("Settings", "exludedSkinsAuthLevel", 2));
            accessOverrideAuthLevel = Convert.ToInt32(GetConfig("Settings", "accessOverrideAuthLevel", 2));
            hideQuickSort = Convert.ToBoolean(GetConfig("Settings", "hideQuickSort", true));
            allowStackedItems = Convert.ToBoolean(GetConfig("Settings", "allowStackedItems", false));
            steamApiKey = Convert.ToString(GetConfig("Settings", "steamApiKey", "https://steamcommunity.com/dev/apikey << get it THERE and saved it HERE"));
            enableCustomPerms = Convert.ToBoolean(GetConfig("CustomPermissions", "enableCustomPerms", false));
            permCustomPlayerwearable = Convert.ToString(GetConfig("CustomPermissions", "permCustomPlayerwearable", "skinbox.playerwearable"));
            permCustomWeapon = Convert.ToString(GetConfig("CustomPermissions", "permCustomWeapon", "skinbox.weapon"));
            permCustomDeployable = Convert.ToString(GetConfig("CustomPermissions", "permCustomDeployable", "skinbox.deployable"));
            enableCooldown = Convert.ToBoolean(GetConfig("Cooldown", "enableCooldown", false));
            cooldownBox = Convert.ToInt32(GetConfig("Cooldown", "cooldownBox", 60));
            cooldownOverrideAdmin = Convert.ToBoolean(GetConfig("Cooldown", "cooldownOverrideAdmin", true));
            cooldownOverrideAuthLevel = Convert.ToInt32(GetConfig("Cooldown", "cooldownOverrideAuthLevel", 2));
            activateAfterSkinTaken = Convert.ToBoolean(GetConfig("Cooldown", "activateAfterSkinTaken", true));
            manualAddedSkinsPre = (Dictionary<string, object>) GetConfig("SkinsAdded", "SkinList", new Dictionary<string, object> { });
            excludedSkinsPre = (List<object>) GetConfig("SkinsExcluded", "SkinList", new List<object> { });
            enableUsageCost = Convert.ToBoolean(GetConfig("UsageCost", "enableUsageCost", false));
            useServerRewards = Convert.ToBoolean(GetConfig("UsageCost", "useServerRewards", true));
            useEconomics = Convert.ToBoolean(GetConfig("UsageCost", "useEconomics", false));
            costBoxOpen = Convert.ToInt32(GetConfig("UsageCost", "costBoxOpen", 5));
            costWeapon = Convert.ToInt32(GetConfig("UsageCost", "costWeapon", 30));
            costPlayerwearable = Convert.ToInt32(GetConfig("UsageCost", "costPlayerwearable", 20));
            costDeployable = Convert.ToInt32(GetConfig("UsageCost", "costDeployable", 10));
            costExcludeAdmins = Convert.ToBoolean(GetConfig("UsageCost", "costExcludeAdmins", true));
            costExcludePerm = Convert.ToString(GetConfig("UsageCost", "costExcludePerm", "skinbox.costexcluded"));
            costExcludePermEnabled = Convert.ToBoolean(GetConfig("UsageCost", "costExcludePermEnabled", false));
            bool configremoval = false;
            if ((Config.Get("AvailableSkins") as Dictionary<string, object>).ContainsKey("useWebskinsRankedByTrend"))
            {
                (Config.Get("AvailableSkins") as Dictionary<string, object>).Remove("useWebskinsRankedByTrend");
                (Config.Get("AvailableSkins") as Dictionary<string, object>).Remove("usedRankedByTrendDays");
                (Config.Get("AvailableSkins") as Dictionary<string, object>).Remove("usedConnectionsToWorkshop");
                configremoval = true;
            }

            if (!Changed & !configremoval)
                return;
            SaveConfig();
            Changed = false;
            configremoval = false;
        }

        protected override void LoadDefaultConfig()
        {
            Config.Clear();
            LoadVariables();
        }

        protected override void LoadDefaultMessages()
        {
            lang.RegisterMessages(
                new Dictionary<string, string>
                {
                    {"NoPermission", "You don't have permission to use the SkinBox"},
                    {"ToNearPlayer", "The SkinBox is currently not usable at this place"},
                    {"CooldownTime", "You need to wait {0} seconds to re-open the SkinBox again"},
                    {"NotEnoughBalanceOpen", "You need at least '{0}' bucks to open the SkinBox"},
                    {"NotEnoughBalanceUse", "You would need at least '{0}' bucks to skin '{1}'"},
                    {"NotEnoughBalanceTake", "'{0}' was not skinned.You had not enough bucks"},
                }, this);
        }

        private void Loaded()
        {
            LoadVariables();
            LoadDefaultMessages();
            if (allowStackedItems) SbscrbSplt();
            else UnsbscrbSplt();

            cmd.AddChatCommand(skinBoxCommand, this, "cmdSknBx");

            for (int i = 0; i < altSkinBoxCommand.Count; i++)
                cmd.AddChatCommand(altSkinBoxCommand[i].ToString(), this, "cmdSknBx");

            permission.RegisterPermission(permissionUse, this);
            permission.RegisterPermission(permCustomPlayerwearable, this);
            permission.RegisterPermission(permCustomWeapon, this);
            permission.RegisterPermission(permCustomDeployable, this);
            permission.RegisterPermission(costExcludePerm, this);
            skinsCache = new Dictionary<string, LinkedList<ulong>>();
            skinsCacheLimited = new Dictionary<string, LinkedList<ulong>>();
            approvedSkinsCount = new Dictionary<string, int>();
            NameToItemName = new Dictionary<string, string>();
            ItemNameToName = new Dictionary<string, string>();
            skinsLoaded = false;
            skinBox = this;
            if (maxPagesShown < 1) maxPagesShown = 1;
            maxItemsShown = 42 * maxPagesShown;
        }

        private void Unload()
        {
            List<SBH> objs = UnityEngine.Object.FindObjectsOfType<SBH>().ToList();
            if (objs.Count > 0)
                foreach (SBH obj in objs)
                {
                    if (obj.looter == null) continue;
                    obj.looter.EndLooting();
                    obj.PlayerStoppedLooting(obj.looter);
                    UnityEngine.Object.Destroy(obj);
                }

            if (Interface.Oxide.IsShuttingDown) return;
        }

        private void OnServerInitialized()
        {
            if (steamApiKey == null || steamApiKey == string.Empty || steamApiKey.Length != 32)
            {
                PrintWarning(_("FxvaObk pbasvt arrqf `fgrnzNcvXrl` sebz `uggcf://fgrnzpbzzhavgl.pbz/qri/ncvxrl` >> Cyhtva haybnqrq"));
                Interface.Oxide.UnloadPlugin(Name);
                return;
            }

            if (enableUsageCost)
            {
                if (ServerRewards != null && useServerRewards) activeServerRewards = true;
                if (Economics != null && useEconomics) activeEconomics = true;
                if (activeServerRewards && activeEconomics) activeEconomics = false;
                if (activeServerRewards || activeEconomics) activePointSystem = true;
            }

            if (allowStackedItems && StacksExtended)
            {
                _stacksExtendedExtrasDisabled = (bool) StacksExtended.CallHook("DisableExtraFeatures");
                if (!_stacksExtendedExtrasDisabled)
                {
                    Unsubscribe(nameof(CanStackItem));
                    Unsubscribe(nameof(OnItemSplit));
                }
                else
                {
                    Subscribe(nameof(CanStackItem));
                    Subscribe(nameof(OnItemSplit));
                }
            }

            foreach (Skinnable skin in Skinnable.All.ToList())
            {
                if (skin.Name == null || skin.Name == string.Empty) continue;
                if (skin.ItemName == null || skin.ItemName == string.Empty) continue;
                if (!NameToItemName.ContainsKey(skin.Name.ToLower()))
                    NameToItemName.Add(skin.Name.ToLower(), skin.ItemName.ToLower());
                if (!ItemNameToName.ContainsKey(skin.ItemName.ToLower()))
                    ItemNameToName.Add(skin.ItemName.ToLower(), skin.Name.ToLower());
            }

            excludedSkins = excludedSkinsPre.ConvertAll(obj => Convert.ToUInt64(obj));
            Puts(_("FxvaObk pbzznaq bireivrj: > fxvaobk.pzqf <"));
            if (useManualAddedSkins)
            {
                List<ulong> s = new List<ulong>();
                foreach (KeyValuePair<string, object> m in manualAddedSkinsPre)
                    s.AddRange((m.Value as List<object>).ConvertAll(obj => Convert.ToUInt64(obj)));

                Puts(_("Dhrelvat Fgrnz sbe znahnyyl nqqrq jbexfubc fxvaf"));               
                CllMnlSkinsWb(s, 0);
            }
            else
            {
                GtItmSkns();
            }

            Initialized = true;
        }

        private void FnllyLdd()
        {
            skinsLoaded = true;
            Puts(_("Cyhtva unf svavfurq vzcbegvat nyy fxvaf"));
        }

        private void GtItmSkns()
        {
            if ((Steamworks.SteamInventory.Definitions?.Length ?? 0) == 0)
            {
                PrintWarning("Waiting for Steamworks to update item definitions....");
                Steamworks.SteamInventory.OnDefinitionsUpdated += GtItmSkns;
                return;
            }

            Steamworks.SteamInventory.OnDefinitionsUpdated -= GtItmSkns;

            int countInbuilt = 0;
            foreach (ItemDefinition itemDef in ItemManager.GetItemDefinitions())
            {
                List<ulong> skins = new List<ulong> {0};
                if (useInbuiltSkins)
                    skins.AddRange(ItemSkinDirectory.ForItem(itemDef).Select(skin => Convert.ToUInt64(skin.id)));
                skinsCache.Add(itemDef.shortname, new LinkedList<ulong>(skins));
                if (skins.Count > 1) countInbuilt += skins.Count - 1;
            }

            if (showLoadedSkinCounts && useInbuiltSkins) Puts(_("Ybnqrq {0} vaohvyg fxvaf"), countInbuilt);
            if (useManualAddedSkins)
            {
                int countManual = 0;
                foreach (KeyValuePair<string, List<ulong>> manualskins in manualAddedSkins)
                {
                    string shortname = manualskins.Key;
                    if (!ItemNameToName.ContainsKey(shortname)) continue;
                    string itemname = ItemNameToName[shortname];
                    List<ulong> fileids = manualskins.Value;
                    foreach (ulong fileid in fileids)
                    {
                        if (!skinsCache.ContainsKey(shortname))
                        {
                            skinsCache.Add(shortname, new LinkedList<ulong>());
                            skinsCache[shortname].AddFirst(0);
                        }

                        if (!skinsCache[shortname].Contains(fileid))
                        {
                            skinsCache[shortname].AddAfter(skinsCache[shortname].First, fileid);
                            countManual++;
                        }
                    }
                }

                if (showLoadedSkinCounts && countManual > 0) Puts(_("Ybnqrq {0} znahny nqqrq fxvaf"), countManual);
            }

            if (useApprovedSkins)
            {
                ChckApprvdSkns();
                return;
            }

            FnllyLdd();
        }

        private string BldDtlsSt(List<ulong> list, int pg)
        {
            int st = pg * 100;
            int ed = st + 100 > list.Count ? list.Count : st + 100;

            string details = string.Format(_("?xrl={0}&vgrzpbhag={1}"), steamApiKey, ed - st);

            for (int i = st; i < ed; i++)
                details += string.Format(_("&choyvfurqsvyrvqf[{0}]={1}"), i - st, list[i]);

            return details;
        }

        private void CllMnlSkinsWb(List<ulong> i, int pg)
        {
            int ttlPgs = Mathf.CeilToInt((float)i.Count / 100f) - 1;

            string b = BldDtlsSt(i, pg);

            try
            {
                webrequest.Enqueue(u1, b, (cd, res) => ServerMgr.Instance.StartCoroutine(PrfMnlSkinsWb(cd, res, i, pg, ttlPgs)), this, RequestMethod.POST);
            }
            catch
            {
                GtItmSkns();
            }
        }

        private IEnumerator PrfMnlSkinsWb(int cd, string res, List<ulong> i, int pg, int ttlPgs)
        {
            if (res != null && cd == 200)
            {
                GtPblshdFlDtls pfd = JsonConvert.DeserializeObject<GtPblshdFlDtls>(res);
                if (pfd != null && pfd.response != null && pfd.response.publishedfiledetails?.Count > 0)
                {
                    Puts(string.Format(_("Cebprffvat jbexfubc erfcbafr.Cntr: {0} / {1}"), pg + 1, ttlPgs + 1));
                    foreach (GtPblshdFlDtls.Response.Publishedfiledetail det in pfd.response.publishedfiledetails)
                    {
                        if (det.tags != null && det.tags.Count > 2)
                        {
                            foreach (GtPblshdFlDtls.Tag tag in det.tags)
                            {
                                string t = tag.tag.ToLower();
                                string sn = string.Empty;
                                if (NameToItemName.ContainsKey(t)) sn = NameToItemName[t];
                                else continue;
                                skinWorkshopNames[det.publishedfileid] = det.title;

                                if (!manualAddedSkins.ContainsKey(sn))
                                    manualAddedSkins.Add(sn, new List<ulong>());

                                if (!manualAddedSkins[sn].Contains(det.publishedfileid))
                                    manualAddedSkins[sn].Add(det.publishedfileid);
                            }
                        }
                    }

                    yield return CoroutineEx.waitForEndOfFrame;
                    yield return CoroutineEx.waitForEndOfFrame;

                    if (pg < ttlPgs)
                    {
                        CllMnlSkinsWb(i, pg + 1);
                        yield break;
                    }
                }

            }
            if (pg < ttlPgs)
            {
                CllMnlSkinsWb(i, pg + 1);
                yield break;
            }
            else GtItmSkns();
        }

        private void ChckApprvdSkns()
        {           
            int count = 0;
            foreach (InventoryDef item in Steamworks.SteamInventory.Definitions)
            {
                string shortname = item.GetProperty("itemshortname");
                if (string.IsNullOrEmpty(shortname) || item.Id < 100)
                    continue;

                ulong wsid;
                if (!ulong.TryParse(item.GetProperty("workshopid"), out wsid))
                    continue;
                
                skinWorkshopNames[wsid] = item.Name;
                
                if (!approvedSkinsCount.ContainsKey(shortname))
                    approvedSkinsCount[shortname] = 0;

                if (approvedSkinsLimit > 0 && approvedSkinsCount[shortname] >= approvedSkinsLimit)
                {
                    if (!skinsCacheLimited.ContainsKey(shortname))
                        skinsCacheLimited[shortname] = new LinkedList<ulong>();
                    skinsCacheLimited[shortname].AddLast(wsid);
                }

                if (skinsCacheLimited.ContainsKey(shortname) && skinsCacheLimited[shortname].Contains(wsid))
                    continue;

                if (!skinsCache.ContainsKey(shortname))
                    skinsCache[shortname] = new LinkedList<ulong>();

                if (!skinsCache[shortname].Contains(wsid) && skinsCache[shortname].Count < maxItemsShown)
                {
                    skinsCache[shortname].AddLast(wsid);
                    approvedSkinsCount[shortname]++;
                    count++;
                }
            }

            if (showLoadedSkinCounts && count > 0)
                Puts(_("Vzcbegrq {0} nccebirq fxvaf sbe '{1}' glcrf"), count, skinsCache.Where(c => c.Value.Count > 1).ToList().Count);
            FnllyLdd();
        }
        //void ChckApprvdSknsWb(int cd, string res)
        //{
        //    if (res == null || cd != 200)
        //    {
        //        FnllyLdd();
        //        return;
        //    }
        //    var schm = JsonConvert.DeserializeObject<Rust.Workshop.ItemSchema>(res);
        //    if (schm == null || !(schm is Rust.Workshop.ItemSchema) || schm.items.Length == 0)
        //    {
        //        FnllyLdd();
        //        return;
        //    }
        //    int count = 0;
        //    foreach (var item in schm.items)
        //    {
        //        if (string.IsNullOrEmpty(item.itemshortname) || string.IsNullOrEmpty(item.workshopid) || string.IsNullOrEmpty(item.workshopdownload))
        //            continue;
        //        ulong wsid = Convert.ToUInt64(item.workshopid);
        //        skinWorkshopNames[wsid] = item.name;
        //        string shortname = item.itemshortname;
        //        if (!approvedSkinsCount.ContainsKey(shortname))
        //            approvedSkinsCount[shortname] = 0;
        //        if (approvedSkinsLimit > 0 && approvedSkinsCount[shortname] >= approvedSkinsLimit)
        //        {
        //            if (!skinsCacheLimited.ContainsKey(shortname))
        //                skinsCacheLimited[shortname] = new LinkedList<ulong>();
        //            skinsCacheLimited[shortname].AddLast(wsid);
        //        }
        //        if (skinsCacheLimited.ContainsKey(shortname) && skinsCacheLimited[shortname].Contains(wsid))
        //            continue;
        //        if (!skinsCache.ContainsKey(shortname))
        //            skinsCache[shortname] = new LinkedList<ulong>();
        //        if (!skinsCache[shortname].Contains(wsid) && skinsCache[shortname].Count < maxItemsShown)
        //        {
        //            skinsCache[shortname].AddLast(wsid);
        //            approvedSkinsCount[shortname]++;
        //            count++;
        //        }
        //    }
        //    if (showLoadedSkinCounts && count > 0)
        //        Puts(_("Vzcbegrq {0} nccebirq fxvaf sbe '{1}' glcrf"), count, skinsCache.Where(c => c.Value.Count > 1).ToList().Count);
        //    FnllyLdd();
        //}

        [ConsoleCommand("skinbox.cmds")]
        private void cmdListCmds(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("\n> SkinBox command overview <");
            TextTable textTable = new TextTable();
            textTable.AddColumn("Command");
            textTable.AddColumn("Description");
            textTable.AddRow(new string[]
                {"skinbox.addskin", "Does add one or multiple skin-id\'s to the manual skin list"});
            textTable.AddRow(new string[]
                {"skinbox.removeskin", "Does remove one or multiple skin-id\'s from the manual skin list"});
            textTable.AddRow(new string[]
                {"skinbox.addexcluded", "Does add one or multiple skin-id\'s to the exclusion list (for players)"});
            textTable.AddRow(new string[]
                {"skinbox.removeexcluded", "Does remove one or multiple skin-id\'s from the exclusion list"});
            textTable.AddRow(new string[]
                {"skinbox.addcollection", "Adds a whole skin-collection to the manual skins list"});
            textTable.AddRow(new string[]
                {"skinbox.removecollection", "Removes a whole collection from the manual skin list"});
            sb.AppendLine(textTable.ToString());
            SendReply(arg, sb.ToString());
        }

        [ConsoleCommand("skinbox.addskin")]
        private void consoleAddSkin(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            if (arg.Args == null || arg.Args.Length < 1)
            {
                SendReply(arg, "You need to type in one or more Workshop FileId's");
                return;
            }

            List<ulong> fileIds = new List<ulong>();
            for (int i = 0; i < arg.Args.Length; i++)
            {
                ulong fileId = 0uL;
                if (!ulong.TryParse(arg.Args[i], out fileId))
                {
                    SendReply(arg, $"Ignored '{arg.Args[i]}' as of not a number");
                    continue;
                }
                else
                {
                    if (arg.Args[i].Length < 9 || arg.Args[i].Length > 10)
                    {
                        SendReply(arg, $"Ignored '{arg.Args[i]}' as of not 9/10-Digits");
                        continue;
                    }

                    fileIds.Add(fileId);
                }
            }

            CallSkinsImportWeb(fileIds, arg);
        }

        [ConsoleCommand("skinbox.removeskin")]
        private void consoleRemoveSkin(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            if (arg.Args == null || arg.Args.Length < 1)
            {
                SendReply(arg, "You need to type in one or more Workshop FileId's");
                return;
            }

            List<ulong> fileIds = new List<ulong>();
            for (int i = 0; i < arg.Args.Length; i++)
            {
                ulong fileId = 0uL;
                if (!ulong.TryParse(arg.Args[i], out fileId))
                {
                    SendReply(arg, $"Ignored '{arg.Args[i]}' as of not a number");
                    continue;
                }
                else
                {
                    if (arg.Args[i].Length < 9 || arg.Args[i].Length > 10)
                    {
                        SendReply(arg, $"Ignored '{arg.Args[i]}' as of not 9/10-Digits");
                        continue;
                    }

                    fileIds.Add(fileId);
                }
            }

            bool doSave = false;
            int removed = 0;
            foreach (KeyValuePair<string, List<ulong>> addedSkins in manualAddedSkins)
            {
                foreach (ulong fileId in fileIds)
                {
                    if (addedSkins.Value.Contains(fileId))
                    {
                        manualAddedSkins[addedSkins.Key].Remove(fileId);
                        skinsCache[addedSkins.Key].Remove(fileId);
                        removed++;
                        doSave = true;
                    }
                }
            }

            if (doSave)
            {
                string[] keys = manualAddedSkins.Keys.ToArray();
                for (int i = 0; i < keys.Length; i++)
                {
                    manualAddedSkins[keys[i]] = manualAddedSkins[keys[i]].Distinct().ToList();
                }

                Config["SkinsAdded", "SkinList"] = manualAddedSkins;
                Config.Save();
                SendReply(arg, $"Removed {removed} FileId's");
            }
        }

        private void CallSkinsImportWeb(List<ulong> i, ConsoleSystem.Arg arg = null)
        {
            string b = string.Format(_("?xrl={0}&vgrzpbhag={1}"), steamApiKey, i.Count);
            int p = 0;
            foreach (ulong f in i)
            {
                b += string.Format(_("&choyvfurqsvyrvqf[{0}]={1}"), p, f);
                p++;
            }

            try
            {
                webrequest.Enqueue(u1, b, (cd, res) => ProofSkinsImportWeb(cd, res, arg), this, RequestMethod.POST);
            }
            catch
            {
            }
        }

        private void ProofSkinsImportWeb(int cd, string res, ConsoleSystem.Arg arg = null)
        {
            if (res == null || cd != 200)
                return;

            GtPblshdFlDtls pfd = JsonConvert.DeserializeObject<GtPblshdFlDtls>(res);
            if (pfd == null || !(pfd is GtPblshdFlDtls) || pfd.response.result == 0 || pfd.response.resultcount == 0)
                return;

            bool doSave = false;
            foreach (GtPblshdFlDtls.Response.Publishedfiledetail det in pfd.response.publishedfiledetails)
            {
                if (det.tags != null && det.tags.Count > 2)
                {
                    string sn = string.Empty;
                    ulong wsid = det.publishedfileid;

                    foreach (GtPblshdFlDtls.Tag tag in det.tags)
                    {
                        string t = tag.tag.ToLower();
                        if (NameToItemName.ContainsKey(t))
                            sn = NameToItemName[t];
                        else continue;

                        if (manualAddedSkins.ContainsKey(sn))
                        {
                            if (manualAddedSkins[sn].Contains(wsid))
                            {
                                SndRplyCl(arg, $"'{det.title} ({wsid})' was already added");
                                continue;
                            }
                        }

                        if (skinsCache.ContainsKey(sn))
                        {
                            if ((skinsCache[sn] as LinkedList<ulong>).Contains(wsid))
                            {
                                SndRplyCl(arg, $"'{det.title} ({wsid})' belongs already to approved/ranked");
                                continue;
                            }
                        }

                        if (!manualAddedSkins.ContainsKey(sn))
                            manualAddedSkins.Add(sn, new List<ulong>());
                        manualAddedSkins[sn].Add(wsid);

                        if (!skinsCache.ContainsKey(sn))
                        {
                            skinsCache.Add(sn, new LinkedList<ulong>());
                            skinsCache[sn].AddLast(0);
                        }

                        skinsCache[sn].AddAfter(skinsCache[sn].First, wsid);
                        skinWorkshopNames[wsid] = det.title;
                        SndRplyCl(arg, $"'{det.title} ({wsid})' added to the list for '{sn}'");
                        doSave = true;
                    }
                }
            }

            if (doSave)
            {
                string[] keys = manualAddedSkins.Keys.ToArray();
                for (int i = 0; i < keys.Length; i++)                
                    manualAddedSkins[keys[i]] = manualAddedSkins[keys[i]].Distinct().ToList();
                
                Config["SkinsAdded", "SkinList"] = manualAddedSkins;
                Config.Save();
            }
        }

        [ConsoleCommand("skinbox.addexcluded")]
        private void consoleAddExcluded(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            if (arg.Args == null || arg.Args.Length < 1)
            {
                SendReply(arg, "You need to type in one or more Workshop FileId's");
                return;
            }

            List<ulong> fileIds = new List<ulong>();
            for (int i = 0; i < arg.Args.Length; i++)
            {
                ulong fileId = 0uL;
                if (!ulong.TryParse(arg.Args[i], out fileId))
                {
                    SendReply(arg, $"Ignored '{arg.Args[i]}' as of not a number");
                    continue;
                }
                else
                {
                    if (arg.Args[i].Length < 9 || arg.Args[i].Length > 10)
                    {
                        SendReply(arg, $"Ignored '{arg.Args[i]}' as of not 9/10-Digits");
                        continue;
                    }

                    fileIds.Add(fileId);
                }
            }

            int countAdded = 0;
            foreach (ulong fileId in fileIds)
                if (!excludedSkins.Contains(fileId))
                {
                    excludedSkins.Add(fileId);
                    countAdded++;
                }

            if (countAdded > 0)
            {
                Config["SkinsExcluded", "SkinList"] = excludedSkins;
                Config.Save();
                SendReply(arg, $"Added {countAdded} skins to exclusion list");
            }
        }

        [ConsoleCommand("skinbox.removeexcluded")]
        private void consoleRemoveExcluded(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            if (arg.Args == null || arg.Args.Length < 1)
            {
                SendReply(arg, "You need to type in one or more Workshop FileId's");
                return;
            }

            List<ulong> fileIds = new List<ulong>();
            for (int i = 0; i < arg.Args.Length; i++)
            {
                ulong fileId = 0uL;
                if (!ulong.TryParse(arg.Args[i], out fileId))
                {
                    SendReply(arg, $"Ignored '{arg.Args[i]}' as of not a number");
                    continue;
                }
                else
                {
                    if (arg.Args[i].Length < 9 || arg.Args[i].Length > 10)
                    {
                        SendReply(arg, $"Ignored '{arg.Args[i]}' as of not 9/10-Digits");
                        continue;
                    }

                    fileIds.Add(fileId);
                }
            }

            int countRemoved = 0;
            foreach (ulong fileId in fileIds)
                if (excludedSkins.Contains(fileId))
                {
                    excludedSkins.Remove(fileId);
                    countRemoved++;
                }

            if (countRemoved > 0)
            {
                Config["SkinsExcluded", "SkinList"] = excludedSkins;
                Config.Save();
                SndRplyCl(arg, $"Removed {countRemoved} skins from exclusion");
            }
        }

        [ConsoleCommand("skinbox.addcollection")]
        private void consoleAddCollection(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            if (arg.Args == null || arg.Args.Length < 1)
            {
                SendReply(arg, "You need to type in a valid collection id");
                return;
            }

            ulong collId = 0;
            if (!ulong.TryParse(arg.Args[0], out collId))
            {
                SendReply(arg, $"Collection ID not correct: '{arg.Args[0]}' is not a number");
                return;
            }
            else
            {
                if (arg.Args[0].Length < 9 || arg.Args[0].Length > 10)
                {
                    SendReply(arg, $"Collection ID not correct: '{arg.Args[0]}' has not 9/10-Digits");
                    return;
                }
            }

            string b = string.Format(_("?xrl={0}&pbyyrpgvbapbhag=1&choyvfurqsvyrvqf[0]={1}"), steamApiKey, arg.Args[0]);
            try
            {
                webrequest.Enqueue(u2, b, (cd, res) => PstCllbckAdd(cd, res, arg), this, RequestMethod.POST);
            }
            catch
            {
                SndRplyCl(arg, "Steam webrequest failed!");
            }
        }

        public void PstCllbckAdd(int cd, string res, ConsoleSystem.Arg arg = null)
        {
            if (res == null || cd != 200)
            {
                SndRplyCl(arg, "Steam webrequest failed by wrong response!");
                return;
            }

            GtCllctnDtls col = JsonConvert.DeserializeObject<GtCllctnDtls>(res);
            if (col == null || !(col is GtCllctnDtls))
            {
                SndRplyCl(arg, "No Collection data received!");
                return;
            }

            if (col.response.resultcount == 0 || col.response.collectiondetails == null ||
                col.response.collectiondetails.Count == 0 || col.response.collectiondetails[0].result != 1)
            {
                SndRplyCl(arg, "The Steam collection could not be found!");
                return;
            }

            List<ulong> fileIds = new List<ulong>();
            foreach (GtCllctnDtls.Response.Collectiondetail.Child child in col.response.collectiondetails[0].children)
                try
                {
                    fileIds.Add(Convert.ToUInt64(child.publishedfileid));
                }
                catch
                {
                }

            if (fileIds.Count == 0)
            {
                SndRplyCl(arg, "No skin numbers found.Workshop search cancelled.");
                return;
            }

            CallSkinsImportWeb(fileIds, arg);
        }

        [ConsoleCommand("skinbox.removecollection")]
        private void consoleRemoveCollection(ConsoleSystem.Arg arg)
        {
            if (arg.Connection != null && arg.Connection.authLevel < 2) return;
            if (arg.Args == null || arg.Args.Length < 1)
            {
                SendReply(arg, "You need to type in a valid collection id");
                return;
            }

            ulong collId = 0;
            if (!ulong.TryParse(arg.Args[0], out collId))
            {
                SendReply(arg, $"Collection ID not correct: '{arg.Args[0]}' is not a number");
                return;
            }
            else
            {
                if (arg.Args[0].Length < 9 || arg.Args[0].Length > 10)
                {
                    SendReply(arg, $"Collection ID not correct: '{arg.Args[0]}' has not 9/10-Digits");
                    return;
                }
            }

            string b = string.Format(_("?xrl={0}&pbyyrpgvbapbhag=1&choyvfurqsvyrvqf[0]={1}"), steamApiKey, arg.Args[0]);
            try
            {
                webrequest.Enqueue(u2, b, (cd, res) => PostCallbackRemove(cd, res, arg), this, RequestMethod.POST);
            }
            catch
            {
                SndRplyCl(arg, "Steam webrequest failed!");
            }
        }

        public void PostCallbackRemove(int cd, string res, ConsoleSystem.Arg arg = null)
        {
            if (res == null || cd != 200)
            {
                SndRplyCl(arg, "Steam webrequest failed by wrong response!");
                return;
            }

            GtCllctnDtls col = JsonConvert.DeserializeObject<GtCllctnDtls>(res);
            if (col == null || !(col is GtCllctnDtls))
            {
                SndRplyCl(arg, "No Collection data received!");
                return;
            }

            if (col.response.resultcount == 0 || col.response.collectiondetails == null ||
                col.response.collectiondetails.Count == 0 || col.response.collectiondetails[0].result != 1)
            {
                SndRplyCl(arg, "The Steam collection could not be found!");
                return;
            }

            List<ulong> fileIds = new List<ulong>();
            foreach (GtCllctnDtls.Response.Collectiondetail.Child child in col.response.collectiondetails[0].children)
                try
                {
                    fileIds.Add(Convert.ToUInt64(child.publishedfileid));
                }
                catch
                {
                }

            if (fileIds.Count == 0)
            {
                SndRplyCl(arg, "No skin numbers found.Workshop search cancelled.");
                return;
            }

            int removed = 0;
            foreach (KeyValuePair<string, List<ulong>> addSkins in new Dictionary<string, List<ulong>>(manualAddedSkins)
            )
            foreach (ulong skin in addSkins.Value.ToList())
                if (fileIds.Contains(skin))
                {
                    manualAddedSkins[addSkins.Key].Remove(skin);
                    if (skinsCache.ContainsKey(addSkins.Key)) skinsCache[addSkins.Key].Remove(skin);
                    removed++;
                }

            if (removed > 0)
            {
                SndRplyCl(arg, $"Removed '{removed}' manual skins by collection remove.");

                string[] keys = manualAddedSkins.Keys.ToArray();
                for (int i = 0; i < keys.Length; i++)
                    manualAddedSkins[keys[i]] = manualAddedSkins[keys[i]].Distinct().ToList();

                Config["SkinsAdded", "SkinList"] = manualAddedSkins;
                Config.Save();
            }
            else
            {
                SndRplyCl(arg, $"No manual skins to remove by collection remove.");
            }
        }

        [ConsoleCommand("skinbox.open")]
        private void consoleSkinboxOpen(ConsoleSystem.Arg arg)
        {
            if (arg == null) return;
            if (arg.Connection == null)
            {
                if (arg.Args == null || arg.Args.Length == 0)
                {
                    SendReply(arg, $"'skinbox.open' cmd needs a passed steamid ");
                    return;
                }

                ulong argId = 0uL;
                if (!ulong.TryParse(arg.Args[0], out argId))
                {
                    SendReply(arg, $"'skinbox.open' cmd for '{arg.Args[0]}' failed (no valid number)");
                    return;
                }

                BasePlayer argPlayer = BasePlayer.FindByID(argId);
                if (argPlayer == null)
                {
                    SendReply(arg, $"'skinbox.open' cmd for userID '{argId}' failed (player not found)");
                    return;
                }

                if (!argPlayer.inventory.loot.IsLooting()) OpnSknBx(argPlayer);
            }
            else if (arg.Connection != null && arg.Connection.player != null)
            {
                BasePlayer player = arg.Player();
                if (player.inventory.loot.IsLooting()) return;
                if (!(player.IsAdmin || player.net.connection.authLevel >= accessOverrideAuthLevel) &&
                    !permission.UserHasPermission(player.UserIDString, permissionUse))
                {
                    player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
                    return;
                }

                if (!ChckOpnBlnc(player)) return;
                if (enableCooldown && !(cooldownOverrideAdmin &&
                                        (player.IsAdmin ||
                                         player.net.connection.authLevel >= cooldownOverrideAuthLevel)))
                {
                    DateTime now = DateTime.UtcNow;
                    DateTime time;
                    string key = player.UserIDString + "-box";
                    if (cooldownTimes.TryGetValue(key, out time))
                        if (time > now.AddSeconds(-cooldownBox))
                        {
                            player.ChatMessage(string.Format(lang.GetMessage("CooldownTime", this, player.UserIDString),
                                (time - now.AddSeconds(-cooldownBox)).Seconds));
                            return;
                        }
                }

                OpnSknBx(player);
            }
        }

        private void cmdSknBx(BasePlayer player, string command, string[] args)
        {
            if (player.inventory.loot.IsLooting()) return;
            if (!(player.IsAdmin || player.net.connection.authLevel >= accessOverrideAuthLevel) &&
                !permission.UserHasPermission(player.UserIDString, permissionUse))
            {
                player.ChatMessage(lang.GetMessage("NoPermission", this, player.UserIDString));
                return;
            }

            if (!ChckOpnBlnc(player)) return;
            if (enableCooldown && !(cooldownOverrideAdmin &&
                                    (player.IsAdmin || player.net.connection.authLevel >= cooldownOverrideAuthLevel)))
            {
                DateTime now = DateTime.UtcNow;
                DateTime time;
                string key = player.UserIDString + "-box";
                if (cooldownTimes.TryGetValue(key, out time))
                    if (time > now.AddSeconds(-cooldownBox))
                    {
                        player.ChatMessage(string.Format(lang.GetMessage("CooldownTime", this, player.UserIDString),
                            (time - now.AddSeconds(-cooldownBox)).Seconds));
                        return;
                    }
            }

            timer.Once(0.2f, () => { OpnSknBx(player); });
        }

        public bool ChckOpnBlnc(BasePlayer player)
        {
            if (!activePointSystem || costBoxOpen <= 0 || player.IsAdmin && costExcludeAdmins ||
                costExcludePermEnabled && permission.UserHasPermission(player.UserIDString, costExcludePerm))
                return true;
            object getMoney = null;
            if (activeServerRewards) getMoney = (int) (Interface.Oxide.CallHook("CheckPoints", player.userID) ?? 0);
            if (activeEconomics) getMoney = (double) (Interface.Oxide.CallHook("Balance", player.UserIDString) ?? 0.0);
            int playerMoney = 0;
            playerMoney = Convert.ToInt32(getMoney);
            if (playerMoney < costBoxOpen)
            {
                player.ChatMessage(string.Format(lang.GetMessage("NotEnoughBalanceOpen", this, player.UserIDString),
                    costBoxOpen));
                return false;
            }

            if (activeServerRewards) Interface.Oxide.CallHook("TakePoints", player.userID, costBoxOpen);
            if (activeEconomics) Interface.Oxide.CallHook("Withdraw", player.userID, Convert.ToDouble(costBoxOpen));
            return true;
        }

        public bool ChckSknBlnc(BasePlayer player, Item item)
        {
            if (!activePointSystem || player.IsA
// ... [Code preview truncated due to length. Full source in attached file] ...

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