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

FREE XDShop : 1.2.2 1.2.2

Нет прав для скачивания
C#:
using Facepunch;
using Newtonsoft.Json;
using Oxide.Core;
using Oxide.Core.Plugins;
using Oxide.Game.Rust.Cui;
using Oxide.Plugins.XDShopExtensionMethods;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
namespace Oxide.Plugins {
    [Info("XDShop", "DezLife", "1.2.2")]
    [Description("Large easily customizable store")]
    internal class XDShop : RustPlugin {
#region Var
        private static XDShop Instance;
        private static Coroutine ApiLoadImage;
        public static StringBuilder StringBuilderInstance;
        private const bool Ru = true;
        private readonly HashSet<string> _exclude = new HashSet<string> {
            "vehicle.chassis", "vehicle.module", "tool.camera", "fishing.tackle", "blood", "wolfmeat.spoiled", "apple.spoiled", "humanmeat.spoiled", "chicken.spoiled", "meat.pork.burned", "chicken.burned", "deermeat.burned", "wolfmeat.burned", "horsemeat.burned", "humanmeat.burned", "bearmeat.burned", "ammo.rocket.smoke", "blueprintbase", "captainslog", "minihelicopter.repair", "note", "photo", "scraptransportheli.repair", "spiderweb", "spookyspeaker", "habrepair", "door.key", "car.key", "bleach", "ducttape", "glue", "sticks", "skullspikes", "skull.trophy", "map", "battery.small", "coal", "can.beans.empty", "can.tuna.empty", "skull.human", "paper", "researchpaper", "water", "hazmatsuit_scientist_arctic", "attire.banditguard", "scientistsuit_heavy", "frankensteins.monster.01.head", "frankensteins.monster.01.legs", "frankensteins.monster.01.torso", "frankensteins.monster.02.legs", "frankensteins.monster.02.head", "frankensteins.monster.02.torso", "snowmobile", "snowmobiletomaha", "rowboat", "mlrs", "workcart", "submarinesolo", "submarineduo", "rhib", "vehicle.chassis.2mod", "vehicle.chassis.3mod", "vehicle.chassis.4mod", "electric.cabletunnel", "water.salt", "geiger.counter"
        }
        ;
#endregion
#region ReferencePlugins
        [PluginReference]
        private readonly Plugin ImageLibrary, Economics, ServerRewards, IQEconomic, Kits, IQKits, Battles, Duel, ItemCostCalculator, NoEscape;
#region NoEscape
        private bool IsRaid(BasePlayer player) {
            if (NoEscape == null) return false;
            return (bool)NoEscape?.Call("IsBlocked", player);
        }
#endregion
#region Duel
        private bool IsDuel(BasePlayer player) {
            if (Battles) return (bool)Battles?.Call("IsPlayerOnBattle", player.userID);
            else if (Duel) return (bool)Duel?.Call("IsPlayerOnActiveDuel", player);
            else return false;
        }
#endregion
#region ImageLibrary
        private string GetImage(string fileName, ulong skin = 0) {
            string imageId = (string)plugins.Find("ImageLibrary").CallHook("GetImage", fileName, skin);
            if (!string.IsNullOrEmpty(imageId)) return imageId;
            return string.Empty;
        }
#endregion
#endregion
#region Types
        public enum EconomicsType {
            Economics, ServerRewards, IQEconomic, Item
        }
        public enum NotificationType {
            Error, Warning, Success
        }
        public enum ThemeType {
            Light, Dark
        }
        public enum ItemType {
            Item, Blueprint, CustomItem, Command, Kit
        }
#endregion
#region Configuration OLD
        private static ConfigurationOld configOld = new ConfigurationOld();
        private class ConfigurationOld {
            [JsonProperty("Предметы")]
            public Dictionary<string, List<ItemStores>> itemstores;
            internal class ItemStores {
                [JsonProperty("Тип предмета(0 - Предмет, 1 - Чертёж, 2 - кастомный предмет, 3 - Команда)")]
                public ItemType type;
                [JsonProperty("Shortame")]
                public string ShortName;
                [JsonProperty("Цена")]
                public int Price;
                [JsonProperty("Количество при покупке")]
                public int Amount;
                [JsonProperty("Кастом имя предмета (Использовать с типом предмета 2 и 3)")]
                public string Name;
                [JsonProperty("SkinID предмета (Использовать с типом предмета 2)")]
                public ulong SkinID;
                [JsonProperty("Команда(Использовать с типом предмета 3)")]
                public string Command;
                [JsonProperty("URL картинки (Использовать с типом предмета 3)")]
                public string Url;
            }
        }
#endregion
#region Configuration
        private Configuration config;
        private class Configuration {
            [JsonProperty(Ru ? "Основные настройки" : "Basic Settings")]
            public MainSettings mainSettings = new MainSettings();
            [JsonProperty(Ru ? "Настройка экономики" : "Economics")]
            public EconomicsCustomization economicsCustomization = new EconomicsCustomization();
            [JsonProperty(Ru ? "Настройка Human NPC" : "Setting up a Human NPC")]
            public HumanNpcs humanNpcs = new HumanNpcs();
            [JsonProperty(Ru ? "Скидки по пермешенам" : "Discounts on permissions")]
            public DiscountStores discountStores = new DiscountStores();
            [JsonProperty(Ru ? "Настройка интерфейса" : "Configuring the interface")]
            public InterfaceSettings interfaceSettings = new InterfaceSettings();
            [JsonProperty(Ru ? "Настройка категорий и товаров" : "Setting up categories and products")]
            public List<CategoryShop> product = new List<CategoryShop>();
            internal class MainSettings {
                [JsonProperty(Ru ? "Команды для открытия магазина (чат)" : "Commands for opening a store (chat)", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                public string[] commands = {
                    "shop"
                }
                ;
                [JsonProperty(Ru ? "Запрещать покупать/продавать во время рейд/комбат блока?" : "Prohibit buying/selling during a raid/combat block?")]
                public bool raidBlock = true;
                [JsonProperty(Ru ? "Разрешения для использования шопа (Оставьте пустым если хотите дать доступ всем игрокам)(пример xdshop.use)" : "Permissions to use the shop (Leave empty if you want to give access to all players)(example xdshop.use)")]
                public string permissionUseShop = "";
            }
            internal class InterfaceSettings {
                [JsonProperty(Ru ? "Включить возможность менять тему?" : "Enable the ability to change the theme?")]
                public bool useChangeTheme = true;
                [JsonProperty(Ru ? "Тема по умолчанию (0 - светлая, 1 - темная)" : "Default theme (0 - light, 1 - dark)")]
                public ThemeType themeTypeDefault = ThemeType.Dark;
                [JsonProperty(Ru ? "Настройки светлой темы UI" : "Light Theme UI Settings")]
                public ThemeCustomization lightTheme = new ThemeCustomization {
                    colorMainBG = "1 1 1 1", colorTextTitle = "0 0 0 1", colorImgTitle = "0 0 0 1", colorImgDiscount = "0.20 0.85 0.15 1.00", colorTextDiscount = "0 0 0 1", colorImgBalance = "0.26 0.53 0.80 1", colorTextBalance = "0 0 0 1", colortext1 = "0 0 0 1", color1 = "0.51 0.51 0.51 1.00", colortext2 = "0.627451 0.6313726 0.6392157 1", colortext3 = "0 0 0 1", colortext6 = "0.97 0.97 0.98 1.00", colortext7 = "0 0 0 1", colortext8 = "0.38 0.77 0.43 1.00", colortext9 = "0.8588235 0.345098 0.3372549 1", color2 = "0.5607843 0.8901961 0.4705883 0.6", color3 = "0.4078432 0.4313726 0.4392157 0.6", colortext10 = "0 0 0 1", colortext4 = "0.51 0.51 0.51 1.00", colortext5 = "0.55 0.55 0.55 1.00", closeBtnColor = "0.8392158 0.3647059 0.3568628 1", closeBtnColor2 = "0.8392158 0.3647059 0.3568628 1"
                }
                ;
                [JsonProperty(Ru ? "Настройки темной темы UI" : "Dark Theme UI Settings")]
                public ThemeCustomization darkTheme = new ThemeCustomization {
                    colorMainBG = "0.13 0.15 0.16 1.00", colorTextTitle = "0.87 0.87 0.87 1.00", colorImgTitle = "0.62 0.63 0.64 1.00", colorImgDiscount = "0.20 0.85 0.15 1.00", colorTextDiscount = "1 1 1 1", colorImgBalance = "0.26 0.53 0.80 1", colorTextBalance = "1 1 1 1", colortext1 = "0.87 0.87 0.87 1.00", color1 = "0.51 0.51 0.51 1.00", colortext2 = "0.627451 0.6313726 0.6392157 1", colortext3 = "0.87 0.87 0.87 1.00", colortext6 = "0.17 0.18 0.21 1.00", colortext7 = "0.87 0.87 0.87 1.00", colortext8 = "0.38 0.77 0.43 1.00", colortext9 = "0.8588235 0.345098 0.3372549 1", color2 = "0.5607843 0.8901961 0.4705883 0.6", color3 = "0.4078432 0.4313726 0.4392157 0.6", colortext10 = "1 1 1 1", colortext4 = "0.51 0.51 0.51 1.00", colortext5 = "0.55 0.55 0.55 1.00", closeBtnColor = "0.8392158 0.3647059 0.3568628 1", closeBtnColor2 = "0.8392158 0.3647059 0.3568628 1",
                }
                ;
                internal class ThemeCustomization {
                    [JsonProperty(Ru ? "Цвет основного фона магазина" : "The color of the main background of the store")]
                    public string colorMainBG = "1 1 1 1";
                    [JsonProperty(Ru ? "[TITLE] Цвет текста" : "[TITLE] Text color")]
                    public string colorTextTitle = "0 0 0 1";
                    [JsonProperty(Ru ? "[TITLE] Цвет картинки" : "[TITLE] Picture Color")]
                    public string colorImgTitle = "0 0 0 1";
                    [JsonProperty(Ru ? "Цвет картинки скидки" : "Color of the discount picture")]
                    public string colorImgDiscount = "0.20 0.85 0.15 1.00";
                    [JsonProperty(Ru ? "Цвет текста скидки" : "Discount text color")]
                    public string colorTextDiscount = "0 0 0 1";
                    [JsonProperty(Ru ? "Цвет картинки баланса" : "Balance picture color")]
                    public string colorImgBalance = "0.26 0.53 0.80 1";
                    [JsonProperty(Ru ? "Цвет текста баланса" : "Balance text color")]
                    public string colorTextBalance = "0 0 0 1";
                    [JsonProperty(Ru ? "[PAGE] Цвет текста номера страниц" : "[PAGE] Page number text color")]
                    public string colortext1 = "0 0 0 1";
                    [JsonProperty(Ru ? "[PAGE] Цвет кнопок переключения страниц" : "[PAGE] Color of the page switching buttons")]
                    public string color1 = "0.51 0.51 0.51 1.00";
                    [JsonProperty(Ru ? "[PRODUCT] Цвет количества предметов (цифры)" : "[PRODUCT] color of the number of items (digits)")]
                    public string colortext2 = "0.627451 0.6313726 0.6392157 1";
                    [JsonProperty(Ru ? "[PRODUCT] Цвет фона товара" : "[PRODUCT] product background color")]
                    public string colortext6 = "0.97 0.97 0.98 1.00";
                    [JsonProperty(Ru ? "[PRODUCT] Цвет текста названия товара" : "[PRODUCT] Text color of the product name")]
                    public string colortext7 = "0 0 0 1";
                    [JsonProperty(Ru ? "[PRODUCT] Цвет кнопки купить" : "[PRODUCT] Buy button color")]
                    public string colortext8 = "0.38 0.77 0.43 1.00";
                    [JsonProperty(Ru ? "[PRODUCT] Цвет кнопки продать" : "[PRODUCT] Color of the sell button")]
                    public string colortext9 = "0.8588235 0.345098 0.3372549 1";
                    [JsonProperty(Ru ? "[PRODUCT] Цвет кнопки закрыть" : "[PRODUCT] Close button color")]
                    public string closeBtnColor2 = "0.8392158 0.3647059 0.3568628 1";
                    [JsonProperty(Ru ? "[CATEGORY] цвет названия активной категории" : "[CATEGORY] color of the name of the active category")]
                    public string colortext3 = "0 0 0 1";
                    [JsonProperty(Ru ? "[CATEGORY] Цвет названия неактивной категорий" : "[CATEGORY] Color of the inactive category name")]
                    public string colortext4 = "0.51 0.51 0.51 1.00";
                    [JsonProperty(Ru ? "[CATEGORY] Цвет полосы активной категории" : "[CATEGORY] Band color of the active category")]
                    public string color2 = "0.5607843 0.8901961 0.4705883 0.6";
                    [JsonProperty(Ru ? "[CATEGORY] Цвет полосы неактивной категории" : "[CATEGORY] Color of the inactive category stripe")]
                    public string color3 = "0.4078432 0.4313726 0.4392157 0.6";
                    [JsonProperty(Ru ? "[NOTIFICATIONS] Цвет текста в уведомлении" : "[NOTIFICATIONS] The color of the text in the notification")]
                    public string colortext10 = "0 0 0 1";
                    [JsonProperty(Ru ? "Цвет дополнительного серого текста" : "Color of additional gray text")]
                    public string colortext5 = "0.55 0.55 0.55 1.00";
                    [JsonProperty(Ru ? "Цвет кнопки выход из UI" : "The color of the exit UI button")]
                    public string closeBtnColor = "0.8392158 0.3647059 0.3568628 1";
                }
            }
            internal class HumanNpcs {
                [JsonProperty(Ru ? "Включить поддержку Human NPC ?" : "Enable Human NPC support ?")]
                public bool useHumanNpcs = false;
                [JsonProperty(PropertyName = "Human NPC  [NPC ID | list shop category]")]
                public Dictionary<string, List<string>> NPCs = new Dictionary<string, List<string>>();
            }
            internal class DiscountStores {
                [JsonProperty(Ru ? "Пермешен/Скидка в %" : "Permissions/Discount in %", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                public Dictionary<string, float> DiscountPerm = new Dictionary<string, float> {
                    ["XDShop.vip"]
                    = 10.0f
                }
                ;
            }
            internal class EconomicsCustomization {
                [JsonProperty(Ru ? "Экономика (0 - Economics, 1 - ServerRewards, 2 - IQEconomic, 3 - Item)" : "Economics (0 - Economics, 1 - ServerRewards, 2 - IQEconomic, 3 - Item)")]
                public EconomicsType typeEconomic = EconomicsType.IQEconomic;
                [JsonProperty(Ru ? "Приставка к балансу (например RP или $ - Не более 2 символов)" : "Prefix to the balance (for example, RP or $ - No more than 2 characters)")]
                public string prefixBalance = "$";
                [JsonProperty(Ru ? "ShortName предмета (Использовать с типом 3)" : "Item shortname (Use with type 3)")]
                public string economicShortname = "";
                [JsonProperty(Ru ? "SkinId предмета (Использовать с типом 3)" : "Item SkinId (Use with Type 3)")]
                public ulong economicSkinId = 0;
            }
            internal class CategoryShop {
                [JsonProperty(Ru ? "Названия категории" : "Category names")]
                public string CategoryName;
                [JsonProperty(Ru ? "Разрешения для доступа к категории" : "Permissions to access the category")]
                public string PermissionCategory;
                [JsonProperty(Ru ? "Список товаров в данной категории" : "List of products in this category")]
                public List<Product> product = new List<Product>();
                internal class Product {
                    [JsonProperty(Ru ? "Тип предмета (0 - Предмет, 1 - Чертёж, 2 - Кастомный предмет, 3 - Команда, 4 - Кит)" : "Item Type (0 - Item, 1 - BluePrint, 2 - Custom item, 3 - Commands, 4 - Kit)")]
                    public ItemType type;
                    [JsonProperty(Ru ? "Уникальный ID (НЕ ТРОГАТЬ)" : "Unique ID (DO NOT TOUCH)")]
                    public int ID = 0;
                    [JsonProperty(Ru ? "Shortame" : "Shortame")]
                    public string ShortName;
                    [JsonProperty(Ru ? "Описания" : "Descriptions")]
                    public string Descriptions;
                    [JsonProperty(Ru ? "Цена" : "Price")]
                    public float Price;
                    [JsonProperty(Ru ? "Цена продажи (Если не нужно то оставьте 0)" : "Sale price (If not necessary, leave 0)")]
                    public float PriceSales;
                    [JsonProperty(Ru ? "Количество" : "Quantity")]
                    public int Amount;
                    [JsonProperty(Ru ? "Количество для продажи" : "Quantity for sale")]
                    public int AmountSales;
                    [JsonProperty(Ru ? "Кастом имя предмета (Использовать с типом предмета 2 , 3 и 4)" : "Custom item name (Use with item type 2, 3 and 4)")]
                    public string Name;
                    [JsonProperty(Ru ? "SkinID предмета (Использовать с типом предмета 2)" : "Item SkinID (Use with item type 2)")]
                    public ulong SkinID;
                    [JsonProperty(Ru ? "Команды (Использовать с типом предмета 3)" : "Commands (Use with item type 3)", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                    public List<string> Commands = new List<string>();
                    [JsonProperty(Ru ? "URL картинки" : "Image URL")]
                    public string Url;
                    [JsonProperty(Ru ? "Кит (Kits - kit name.IQKits - kit key)" : "Kits (Kits - kit name.IQKits - kit key)")]
                    public string KitName;
                    [JsonProperty(Ru ? "Задержка покупки (0 - неограниченно)" : "Purchase delay (0 - unlimited)")]
                    public float BuyCooldown;
                    [JsonProperty(Ru ? "Задержка продажи (0 - неограниченно)" : "Sale delay (0 - unlimited)")]
                    public float SellCooldown;
                    [JsonProperty(Ru ? "Максимальное количество лотов за 1 покупку (Максимум 99)" : "Maximum number of lots for 1 purchase (Maximum 99)", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                    public Dictionary<string, int> BuyLimits = new Dictionary<string, int>();
                    [JsonProperty(Ru ? "Максимальное количество лотов за 1 продажу (Максимум 99)" : "Maximum number of lots for 1 sale (Maximum 99)", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                    public Dictionary<string, int> SellLimits = new Dictionary<string, int>();
                    [JsonProperty(Ru ? "Максимальное количество покупаемых лотов за вайп (0 - неограниченно)" : "The maximum number of purchased lots per wipe (0 - unlimited)", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                    public Dictionary<string, int> BuyLimitsWipe = new Dictionary<string, int>();
                    [JsonProperty(Ru ? "Максимальное количество продаваемых лотов за вайп (0 - неограниченно)" : "The maximum number of lots sold per wipe (0 - unlimited)", ObjectCreationHandling = ObjectCreationHandling.Replace)]
                    public Dictionary<string, int> SellLimitsWipe = new Dictionary<string, int>();
                    [JsonIgnore]
                    public ItemDefinition Definition;
                    [JsonIgnore]
                    public bool ItemsErorred = false;
                    public string GetProductName(string UserId) {
                        string userLang = Instance.lang.GetLanguage(UserId);
                        if (!string.IsNullOrWhiteSpace(Name)) return Name;
                        if (!string.IsNullOrWhiteSpace(ShortName) && Instance.ItemName.ContainsKey(ShortName)) return userLang == "ru" ? Instance.ItemName[ShortName].ru : Instance.ItemName[ShortName].en;
                        return string.Empty;
                    }
                    public string GetProductDescription() {
                        if (!string.IsNullOrWhiteSpace(Descriptions)) return Descriptions;
                        if (!string.IsNullOrWhiteSpace(ShortName) && Instance.ItemName.ContainsKey(ShortName) && !string.IsNullOrWhiteSpace(Instance.ItemName[ShortName].description)) return Instance.ItemName[ShortName].description;
                        return string.Empty;
                    }
                    public int GetLimitLot(BasePlayer player, bool purchase) {
                        Dictionary<string, int> dict = purchase ? BuyLimits : SellLimits;
                        int Limit = 0;
                        if (dict.Count == 0) return Limit;
                        foreach (KeyValuePair<string, int> Discount in dict) if (Instance.permission.UserHasPermission(player.UserIDString, Discount.Key)) if (Limit < Discount.Value) Limit = Discount.Value;
                        return Limit;
                    }
                    public int GetLimitLotWipe(BasePlayer player, bool purchase) {
                        Dictionary<string, int> dict = purchase ? BuyLimitsWipe : SellLimitsWipe;
                        int Limit = 0;
                        if (dict.Count == 0) return Limit;
                        foreach (KeyValuePair<string, int> Discount in dict) if (Instance.permission.UserHasPermission(player.UserIDString, Discount.Key)) if (Limit < Discount.Value) Limit = Discount.Value;
                        return Limit;
                    }
                }
            }
        }
        protected override void LoadConfig() {
            base.LoadConfig();
            try {
                config = Config.ReadObject<Configuration>();
                if (config == null) throw new Exception();
                SaveConfig();
            }
            catch {
                for (int i = 0; i < 3; i++) PrintError("Configuration file is corrupt! Check your config file at https://jsonlint.com/");
                LoadDefaultConfig();
            }
            ValidateConfig();
            CheckOnDuplicates();
            SaveConfig();
        }
        private void ValidateConfig() {
            foreach (Configuration.CategoryShop category in config.product) {
                foreach (Configuration.CategoryShop.Product product in category.product) {
                    foreach (KeyValuePair<string, int> BuyLimits in product.BuyLimits) if (!permission.PermissionExists(BuyLimits.Key)) permission.RegisterPermission(BuyLimits.Key, this);
                    foreach (KeyValuePair<string, int> SellLimits in product.SellLimits) if (!permission.PermissionExists(SellLimits.Key)) permission.RegisterPermission(SellLimits.Key, this);
                    foreach (KeyValuePair<string, int> BuyLimitsWipe in product.BuyLimitsWipe) if (!permission.PermissionExists(BuyLimitsWipe.Key)) permission.RegisterPermission(BuyLimitsWipe.Key, this);
                    foreach (KeyValuePair<string, int> SellLimitsWipe in product.SellLimitsWipe) if (!permission.PermissionExists(SellLimitsWipe.Key)) permission.RegisterPermission(SellLimitsWipe.Key, this);
                }
                if (!permission.PermissionExists(category.PermissionCategory)) permission.RegisterPermission(category.PermissionCategory, this);
            }
        }
        private void CheckingProducts() {
            foreach (Configuration.CategoryShop category in config.product) {
                foreach (Configuration.CategoryShop.Product product in category.product) {
                    if (product.ID == 0) product.ID = Core.Random.Range(int.MinValue, int.MaxValue);
                    if (product.type == ItemType.Item || product.type == ItemType.Blueprint || product.type == ItemType.CustomItem) {
                        product.Definition = ItemManager.FindItemDefinition(product.ShortName);
                        if (product.Definition == null) {
                            product.ItemsErorred = true;
                            PrintError(GetLang("XDSHOP_SERVICE_CONFIG_1", args : product.ID));
                            continue;
                        }
                    }
                    if (product.Price <= 0) {
                        product.ItemsErorred = true;
                        PrintError(GetLang("XDSHOP_SERVICE_CONFIG_2", args : product.ID));
                        continue;
                    }
                }
            }
        }
        protected override void SaveConfig() {
            Config.WriteObject(config);
        }
        protected override void LoadDefaultConfig() {
            config = new Configuration();
        }
#endregion
#region Lang
        protected override void LoadDefaultMessages() {
            lang.RegisterMessages(new Dictionary<string, string> {
                ["XDSHOP_UI_TITLE"]
                = "Каталог товаров", ["XDSHOP_UI_BTN_BUY"] = "Купить", ["XDSHOP_UI_BTN_SALLE"] = "Продать", ["XDSHOP_UI_PRODUCT_INFO"] = "Цена покупки: {0}\nКоличество: {1}\nВаш лимит: {2}", ["XDSHOP_UI_PRODUCT_INFO_EXIT"] = "ЗАКРЫТЬ", ["XDSHOP_UI_PRODUCT_SELL_INFO"] = "Цена продажи: {0}\nКоличество : {1}\nВаш лимит: {2}", ["XDSHOP_UI_NOTIFICATION_IS_DUEL"] = "Вы не можете приобрести предмет во время дуэли!", ["XDSHOP_UI_NOTIFICATION_IS_RAID"] = "Вы не можете приобрести предмет во время рейд/комбат блока!", ["XDSHOP_UI_NOTIFICATION_NOT_ENOUGH_SPACE"] = "Недостаточно места в инвентаре", ["XDSHOP_UI_NOTIFICATION_INSUFFICIENT_FUNDS"] = "У вас недостаточно средств для данной покупки", ["XDSHOP_UI_NOTIFICATION_BUY_RECHARGE"] = "Вы не можете приобрести '{0}'.Вам нужно подождать еще {1}", ["XDSHOP_UI_NOTIFICATION_BUY_LIMIT"] = "Вы больше не можете приобрести '{0}'.Вы превысили лимит за WIPE", ["XDSHOP_UI_NOTIFICATION_BUY_LIMIT_1"] = "Вы не можете приобрести '{0}' в таком количестве.Вы можете купить еще {1} лот(ов)", ["XDSHOP_UI_NOTIFICATION_SUCCESSFUL_PURCHASE"] = "Вы успешно приобрели {0}", ["XDSHOP_UI_NOTIFICATION_SELL_IS_DUEL"] = "Вы не можете продать предмет во время дуэли!", ["XDSHOP_UI_NOTIFICATION_SELL_IS_RAID"] = "Вы не можете продать предмет во время рейд/комбат блока!", ["XDSHOP_UI_NOTIFICATION_NOT_ENOUGH_ITEM"] = "Недостаточно предмета для продажи", ["XDSHOP_UI_NOTIFICATION_SELL_RECHARGE"] = "Вы не можете продать '{0}'.Вам нужно подождать еще {1}", ["XDSHOP_UI_NOTIFICATION_SELL_LIMIT"] = "Вы больше не можете продать '{0}'.Вы превысили лимит продаж за WIPE", ["XDSHOP_UI_NOTIFICATION_SELL_LIMIT_1"] = "Вы не можете продать '{0}' в таком количестве.Вы можете продать еще {1} лот(ов)", ["XDSHOP_UI_NOTIFICATION_SUCCESSFUL_SALE"] = "Вы успешно продали {0}", ["XDSHOP_SERVICE_EXIST_ECONOMICS"] = "У вас отсутствует выбранная экономика.Пожалуйста! Проверьте настройки экономики в конфигурации", ["XDSHOP_SERVICE_CONFIG_1"] = "В товаре с ID '{0}' присутствует ошибка.Товар будет скрыт, проверьте правильно ли вы указали ShortName!", ["XDSHOP_SERVICE_CONFIG_2"] = "В товаре с ID '{0}' присутствует ошибка.Товар будет скрыт, у товара отсутствует или неверная цена!", ["XDSHOP_SERVICE_CMD_REFILL"] = "Выполнения данной команды повлечет за собой изменения конфигурации товаров и категорий.Убедитесь что вы сохранили конфигурацию перед данной операцией.Вы уверены, что хотите продолжить? (xdshop.yes или xdshop.no)", ["XDSHOP_SERVICE_CMD_REFILL_YES"] = "Происходит перезаполнение категорий и товаров.Пожалуйста, ожидайте...", ["XDSHOP_SERVICE_CMD_REFILL_NO"] = "Действие успешно отменено.", ["XDSHOP_SERVICE_CMD_REFILL_SUCCESSFULLY"] = "Заполнения магазина товарами прошло успешно.Перезагружаем плагин для более корректной работы.", ["XDSHOP_SERVICE_CMD_LOCK_CATEGORY"] = "Данная категория не доступна для вас!", ["XDSHOP_SERVICE_UPDATE_PLUGINS"] = "Плагин работает некорректно! Обновите плагин до последней версии.", ["XDSHOP_SERVICE_1"] = "Что то пошло не так.Кажется страрая конфигурация сломана.Обратитесь к разработчику!", ["XDSHOP_SERVICE_2"] = "В старой конфигурации отсутсвуют товары!", ["XDSHOP_SERVICE_3"] = "Перестраиваем конфигурацию...", ["XDSHOP_SERVICE_4"] = "Список товаров успешно перестроен! Перезагружаем плагин...", ["XDSHOP_SERVICE_5"] = "У вас недостаточно прав для использования данной команды!", ["XDSHOP_SERVICE_6"] = "В данный момент магазин пуст.", ["XDSHOP_UI_PATTERN"] = "Отсутствует",
            }
            , this, "ru");
            lang.RegisterMessages(new Dictionary<string, string> {
                ["XDSHOP_UI_TITLE"]
                = "Catalog", ["XDSHOP_UI_BTN_BUY"] = "Buy", ["XDSHOP_UI_BTN_SALLE"] = "Sell", ["XDSHOP_UI_PRODUCT_INFO"] = "Purchase Price: {0}\nQuantity: {1}\nYour limit : {2}", ["XDSHOP_UI_PRODUCT_INFO_EXIT"] = "CLOSE", ["XDSHOP_UI_PRODUCT_SELL_INFO"] = "Selling Price: {0}\nQuantity: {1}\nYour limit : {2}", ["XDSHOP_UI_NOTIFICATION_IS_DUEL"] = "You cannot purchase an item during a duel!", ["XDSHOP_UI_NOTIFICATION_IS_RAID"] = "You cannot purchase an item during a raid/combat block!", ["XDSHOP_UI_NOTIFICATION_NOT_ENOUGH_SPACE"] = "Insufficient inventory space", ["XDSHOP_UI_NOTIFICATION_INSUFFICIENT_FUNDS"] = "You do not have enough funds for this purchase", ["XDSHOP_UI_NOTIFICATION_BUY_RECHARGE"] = "You cannot purchase '{0}'.You need to wait some more {1}", ["XDSHOP_UI_NOTIFICATION_BUY_LIMIT"] = "You can no longer purchase '{0}'.You have exceeded the limit for WIPE", ["XDSHOP_UI_NOTIFICATION_BUY_LIMIT_1"] = "You cannot purchase '{0}' in such quantity.You can buy more {1} lot(s)", ["XDSHOP_UI_NOTIFICATION_SUCCESSFUL_PURCHASE"] = "You have successfully purchased {0}", ["XDSHOP_UI_NOTIFICATION_SELL_IS_DUEL"] = "You cannot sell an item during a duel!", ["XDSHOP_UI_NOTIFICATION_SELL_IS_RAID"] = "You cannot sell an item during a raid/combat block!", ["XDSHOP_UI_NOTIFICATION_NOT_ENOUGH_ITEM"] = "Not enough item to sell", ["XDSHOP_UI_NOTIFICATION_SELL_RECHARGE"] = "You cannot sell '{0}'.You need to wait some more {1}", ["XDSHOP_UI_NOTIFICATION_SELL_LIMIT"] = "You can no longer sell '{0}'.You have exceeded the sales limit for WIPE", ["XDSHOP_UI_NOTIFICATION_SELL_LIMIT_1"] = "You cannot sell '{0}' in such quantity.you can sell more {1} lot(s)", ["XDSHOP_UI_NOTIFICATION_SUCCESSFUL_SALE"] = "You have successfully sold {0}", ["XDSHOP_SERVICE_EXIST_ECONOMICS"] = "You are missing the selected economics.Please! Check the economics settings in the configuration", ["XDSHOP_SERVICE_CONFIG_1"] = "Enter product with ID '{0}' There is an error.The product will be hidden, check if you have entered the Short Name correctly!", ["XDSHOP_SERVICE_CONFIG_2"] = "Enter product with ID '{0}' There is an error.The product will be hidden, the product ID is missing or the price is wrong!", ["XDSHOP_SERVICE_CMD_REFILL"] = "Execution of this command will entail changes in the configuration of products and categories.Make sure you save the configuration before this operation.Are you sure you want to continue? (xdshop.yes or xdshop.no)", ["XDSHOP_SERVICE_CMD_REFILL_YES"] = "The categories and products are refilled.Please wait...", ["XDSHOP_SERVICE_CMD_REFILL_NO"] = "Action canceled successfully.", ["XDSHOP_SERVICE_CMD_REFILL_SUCCESSFULLY"] = "Filling the store with goods was successful.Reload the plugin for more correct work.", ["XDSHOP_SERVICE_CMD_LOCK_CATEGORY"] = "This category is not available to you!", ["XDSHOP_SERVICE_UPDATE_PLUGINS"] = "The plugin is not working correctly! Update the plugin to the latest version.", ["XDSHOP_SERVICE_1"] = "Something went wrong.It seems the old configuration is broken.Contact the developer!", ["XDSHOP_SERVICE_2"] = "There are no products in the old configuration!", ["XDSHOP_SERVICE_3"] = "Rebuilding the configuration...", ["XDSHOP_SERVICE_4"] = "The list of products has been successfully rebuilt! Reloading the plugin...", ["XDSHOP_SERVICE_5"] = "You don't have enough rights to use this command!", ["XDSHOP_SERVICE_6"] = "В данный момент магазин пуст.", ["XDSHOP_UI_PATTERN"] = "Absent",
            }
            , this);
        }
        public string GetLang(string LangKey, string userID = null, params object[] args) {
            StringBuilderInstance.Clear();
            if (args != null) {
                StringBuilderInstance.AppendFormat(lang.GetMessage(LangKey, this, userID), args);
                return StringBuilderInstance.ToString();
            }
            return lang.GetMessage(LangKey, this, userID);
        }
#endregion
#region HumanNPC
        private void SubAndUnSubHumanNpcHook(bool sub = false) {
            if (!sub) {
                Unsubscribe(nameof(OnUseNPC));
                Unsubscribe(nameof(OnLeaveNPC));
                Unsubscribe(nameof(OnKillNPC));
            }
            else {
                Subscribe(nameof(OnUseNPC));
                Subscribe(nameof(OnLeaveNPC));
                Subscribe(nameof(OnKillNPC));
            }
        }
        private void OnUseNPC(BasePlayer npc, BasePlayer player) {
            if (config.humanNpcs.NPCs.ContainsKey(npc.UserIDString) && !humanNpcPlayerOpen.ContainsKey(player.userID)) {
                humanNpcPlayerOpen.Add(player.userID, npc.UserIDString);
                XDShopUI(player);
            }
        }
        private void OnLeaveNPC(BasePlayer npc, BasePlayer player) {
            if (config.humanNpcs.NPCs.ContainsKey(npc.UserIDString)) {
                if (humanNpcPlayerOpen.ContainsKey(player.userID)) {
                    humanNpcPlayerOpen.Remove(player.userID);
                    if (uiPlayerUseNow.Contains(player.userID)) uiPlayerUseNow.Remove(player.userID);
                    CuiHelper.DestroyUi(player, "NOTIFICATION_POLOSA");
                    CuiHelper.DestroyUi(player, "NOTIFICATION_IMG");
                    CuiHelper.DestroyUi(player, "NOTIFICATION_TEXT");
                    CuiHelper.DestroyUi(player, NOTIFICATION_MAIN);
                    CuiHelper.DestroyUi(player, MAIN_LAYER);
                }
            }
        }
        private void OnKillNPC(BasePlayer npc, BasePlayer player) {
            if (config.humanNpcs.NPCs.ContainsKey(npc.UserIDString)) {
                foreach (KeyValuePair<ulong, string> item in humanNpcPlayerOpen.Where(x => x.Value == npc.UserIDString)) {
                    if (humanNpcPlayerOpen.ContainsKey(item.Key)) {
                        humanNpcPlayerOpen.Remove(item.Key);
                        if (uiPlayerUseNow.Contains(player.userID)) uiPlayerUseNow.Remove(player.userID);
                        CuiHelper.DestroyUi(player, "NOTIFICATION_POLOSA");
                        CuiHelper.DestroyUi(player, "NOTIFICATION_IMG");
                        CuiHelper.DestroyUi(player, "NOTIFICATION_TEXT");
                        CuiHelper.DestroyUi(player, NOTIFICATION_MAIN);
                        CuiHelper.DestroyUi(player, MAIN_LAYER);
                    }
                }
            }
        }
#endregion
#region Hooks
        private void Unload() {
            SaveLimits();
            SaveCooldowns();
            SavePlayerData();
            foreach (BasePlayer player in BasePlayer.activePlayerList) CuiHelper.DestroyUi(player, MAIN_LAYER);
            ImageUi.Unload();
            if (ApiLoadImage != null) {
                ServerMgr.Instance.StopCoroutine(ApiLoadImage);
                ApiLoadImage = null;
            }
            StringBuilderInstance = null;
            Instance = null;
        }
        private void Init() {
            Instance = this;
            SubAndUnSubHumanNpcHook();
            LoadData();
            foreach (KeyValuePair<string, float> discount in config.discountStores.DiscountPerm) permission.RegisterPermission(discount.Key, this);
            foreach (string command in config.mainSettings.commands) cmd.AddChatCommand(command, this, nameof(XDShopUI));
        }
        private void OnServerInitialized() {
            StringBuilderInstance = new StringBuilder();
            if (!ExistEconomics()) {
                NextTick(() => {
                    PrintError(GetLang("XDSHOP_SERVICE_EXIST_ECONOMICS"));
                    Interface.Oxide.UnloadPlugin(Name);
                }
                );
                return;
            }
            AddDisplayName();
            ImageUi.DownloadImages();
            ApiLoadImage = ServerMgr.Instance.StartCoroutine(DownloadImages());
            CheckingProducts();
            if (!string.IsNullOrWhiteSpace(config.mainSettings.permissionUseShop) && !permission.PermissionExists(config.mainSettings.permissionUseShop)) permission.RegisterPermission(config.mainSettings.permissionUseShop, this);
            if (config.humanNpcs.useHumanNpcs) SubAndUnSubHumanNpcHook(true);
        }
        private void OnPlayerConnected(BasePlayer player) {
            if (!PlayerThemeSelect.ContainsKey(player.userID)) {
                PlayerThemeSelect.Add(player.userID, config.interfaceSettings.themeTypeDefault);
            }
        }
        private void OnPlayerDisconnected(BasePlayer player, string reason) {
            if (uiPlayerUseNow.Contains(player.userID)) uiPlayerUseNow.Remove(player.userID);
            if (config.humanNpcs.useHumanNpcs) if (humanNpcPlayerOpen.ContainsKey(player.userID)) humanNpcPlayerOpen.Remove(player.userID);
        }
        private void OnNewSave(string filename) {
            PlayerDataLimits.Players.Clear();
            PlayerDataCooldowns.Clear();
        }
#endregion
#region UI
        private readonly List<ulong> uiPlayerUseNow = new List<ulong>();
        private readonly Dictionary<ulong, string> humanNpcPlayerOpen = new Dictionary<ulong, string>();
#region Layers
        private const string MAIN_LAYER = "MAIN_SHOP_LAYER";
        private const string PANEL_PRODUCT = "MAIN_PANEL_PRODUCTS";
        private const string CATEGORY_LAYER = "CATEGORY_LAYER";
        private const string PRODUCTS_LAYER = "PRODUCTS_LAYER";
        private const string PAGE_PRODUCTS = "PAGE_PRODUCTS";
        private const string PRODUCT_AMOUNT_CHANGE_BG = "PRODUCT_AMOUNT_CHANGE_BG";
        private const string NOTIFICATION_MAIN = "NOTIFICATION_MAIN";
        private const string CONFIRMATIONS_PANEL = "CONFIRMATIONS_PANEL";
        private const string CONFIRMATIONS_PANEL_SELLING = "CONFIRMATIONS_PANEL_SELLING";
#endregion
#region Main
        private void XDShopUI(BasePlayer player) {
            if (!string.IsNullOrWhiteSpace(config.mainSettings.permissionUseShop) && !permission.UserHasPermission(player.UserIDString, config.mainSettings.permissionUseShop)) {
                player.ChatMessage(GetLang("XDSHOP_SERVICE_5", player.UserIDString));
                return;
            }
            if (GetCategories(player).Count == 0) {
                player.ChatMessage(GetLang("XDSHOP_SERVICE_6", player.UserIDString));
                return;
            }
            if (!uiPlayerUseNow.Contains(player.userID)) uiPlayerUseNow.Add(player.userID);
            else return;
            if (!PlayerThemeSelect.ContainsKey(player.userID)) PlayerThemeSelect.Add(player.userID, config.interfaceSettings.themeTypeDefault);
            ThemeType themeType = PlayerThemeSelect[player.userID];
            CuiElementContainer container = new CuiElementContainer {
                {
                    new CuiPanel {
                        CursorEnabled = true, Image = {
                            Color = "1 1 1 0"
                        }
                        , RectTransform = {
                            AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-528.963 -263.276", OffsetMax = "504.037 268.724"
                        }
                    }
                    , "Overlay", MAIN_LAYER
                }
            }
            ;
            CuiHelper.DestroyUi(player, MAIN_LAYER);
            CuiHelper.AddUi(player, container);
            UIMAIN(player, themeType);
        }
        private void UIMAIN(BasePlayer player, ThemeType themetype) {
            Configuration.InterfaceSettings.ThemeCustomization theme = themetype == ThemeType.Dark ? config.interfaceSettings.darkTheme : config.interfaceSettings.lightTheme;
            float discount = GetUserDiscount(player);
            CuiElementContainer container = new CuiElementContainer();
            container.Add(new CuiElement {
                Name = PANEL_PRODUCT, Parent = MAIN_LAYER, Components = {
                    new CuiRawImageComponent {
                        Color = theme.colorMainBG, Png = ImageUi.GetImage("0")
                    }
                    , new CuiRectTransformComponent {
                        AnchorMin = "0 0", AnchorMax = "1 1"
                    }
                }
            }
            );
            container.Add(new CuiButton {
                Button = {
                    Color = "0 0 0 0", Command = "UI_HandlerShop CLOSE_ALL_UI"
                }
                , Text = {
                    Text = "x", Font = "robotocondensed-bold.ttf", FontSize = 13, Align = TextAnchor.MiddleCenter, Color = theme.closeBtnColor
                }
                , RectTransform = {
                    AnchorMin = "1 1", AnchorMax = "1 1", OffsetMin = "-27.467 -24.554", OffsetMax = "-6.946 -5.983"
                }
            }
            , PANEL_PRODUCT, "CLOSE_MENU_BTN");
#region TITLE
#endregion
            CuiHelper.DestroyUi(player, PANEL_PRODUCT);
            CuiHelper.AddUi(player, container);
            UIPRODUCT(player, themetype);
            UICATEGORY(player, themetype);
            UpdateBalance(player, themetype);
            if (config.interfaceSettings.useChangeTheme) ThemeSwitch(player, themetype);
        }
#endregion
#region Theme switcher
        private void ThemeSwitch(BasePlayer player, ThemeType themetype) {
            return;
        }
#endregion
#region Update Balance
        private void UpdateBalance(BasePlayer player, ThemeType themetype) {
            Configuration.InterfaceSettings.ThemeCustomization theme = themetype == ThemeType.Dark ? config.interfaceSettings.darkTheme : config.interfaceSettings.lightTheme;
            CuiElementContainer container = new CuiElementContainer {
                {
                    new CuiPanel {
                        CursorEnabled = false, Image = {
                            Color = "1 1 1 0"
                        }
                        , RectTransform = {
                            AnchorMin = "1 1", AnchorMax = "1 1", OffsetMin = "-120.947 -146.751", OffsetMax = "-113.693 -118.067"
                        }
                    }
                    , PANEL_PRODUCT, "BALANCE_INFO"
                }
                , {
                    new CuiPanel {
                        CursorEnabled = false, Image = {
                            Color = "0.00 0.44 0.00 0.69"
                        }
                        , RectTransform = {
                            AnchorMin = "1 0.5", AnchorMax = "1 0.5", OffsetMin = "-120.563 -12", OffsetMax = "55.372 12"
                        }
                    }
                    , "BALANCE_INFO", "huy"
                }
                , {
                    new CuiLabel {
                        RectTransform = {
                            AnchorMin = "0 0", AnchorMax = "1 1"
                        }
                        , Text = {
                            Text = "Урана у Вас в инвентаре: " + GetBalance(player).ToString("0"), Font = "robotocondensed-bold.ttf", FontSize = 11, Align = TextAnchor.MiddleCenter, Color = theme.colorTextBalance
                        }
                    }
                    , "huy", "BALANCE"
                }
            }
            ;
            CuiHelper.DestroyUi(player, "BALANCE_INFO");
            CuiHelper.AddUi(player, container);
        }
#endregion
#region Category UI
        private void UICATEGORY(BasePlayer player, ThemeType themetype, int page = 0, int categoryIndex = 0) {
            Configuration.InterfaceSettings.ThemeCustomization theme = themetype == ThemeType.Dark ? config.interfaceSettings.darkTheme : config.interfaceSettings.lightTheme;
            CuiElementContainer container = new CuiElementContainer {
                {
                    new CuiPanel {
                        CursorEnabled = false, Image = {
                            Color = "1 1 1 0"
                        }
                        , RectTransform = {
                            AnchorMin = "0.5 1", AnchorMax = "0.5 1", OffsetMin = "-425.607 -77.449", OffsetMax = "454.613 -46.751"
                        }
                    }
                    , PANEL_PRODUCT, CATEGORY_LAYER
                }
            }
            ;
            int i = 0, catIndex = page * 6;
            List<Configuration.CategoryShop> category = GetCategories(player);
            /*foreach (Configuration.CategoryShop cat in category.Page(page, 6))
            {
                bool thisCat = catIndex == categoryIndex;
                string colorLine = thisCat ? theme.color2 : theme.color3;
                container.Add(new CuiElement
                {
                    Name = $"CATEGORY_{i}",
                    Parent = CATEGORY_LAYER,
                    Components = {
                        new CuiRawImageComponent { Color = colorLine, Png = ImageUi.GetImage("18") },
                        new CuiRectTransformComponent { AnchorMin = "0 0.5", AnchorMax = "0 0.5", OffsetMin = $"{0.912 + (i * 133)} -13.949", OffsetMax = $"{95.559 + (i * 133)} 5.349" }
                    }
                });

                container.Add(new CuiPanel
                {
                    CursorEnabled = false,
                    Image = { Color = colorLine, Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat" },
                    RectTransform = { AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-47.324 -9.649", OffsetMax = "47.324 -8.649" }
                }, $"CATEGORY_{i}", "CATEGORY_LINE");

                container.Add(new CuiButton
                {
                    Button = { Command = thisCat ? "" : $"UI_HandlerShop CHANGE_CATEGORY {page} {catIndex} {themetype}", Color = "0 0 0 0" },
                    Text = { Text = cat.CategoryName, Font = thisCat ? "robotocondensed-bold.ttf" : "robotocondensed-regular.ttf", FontSize = 12, Align = TextAnchor.UpperCenter, Color = thisCat ? theme.colortext3 : theme.colortext4 },
                    RectTransform = { AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-47.323 -9.649", OffsetMax = "47.323 9.649" }
                }, $"CATEGORY_{i}");
                catIndex++;
                if (i >= 5)
                    break;
                i++;
            }*/
#region CATEGORY_PAGE
            /*if (category.Count > 6)
            {
                container.Add(new CuiPanel
                {
                    Image = { Color = "1 1 1 0" },
                    RectTransform = { AnchorMin = "1 1", AnchorMax = "1 1", OffsetMin = "-77.294 -30.698", OffsetMax = "0 0" }
                }, CATEGORY_LAYER, "CATEGORY_PAGE");

                container.Add(new CuiLabel
                {
                    RectTransform = { AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-10.74 -6.965", OffsetMax = "10.74 6.965" },
                    Text = { Text = $"{page + 1}", Font = "robotocondensed-regular.ttf", FontSize = 10, Align = TextAnchor.MiddleCenter, Color = theme.colortext1 },
                }, "CATEGORY_PAGE");

                if (page > 0)
                {
                    container.Add(new CuiElement
                    {
                        Name = "PAGE_LEFT",
                        Parent = "CATEGORY_PAGE",
                        Components = {
                        new CuiRawImageComponent { Color = theme.color1, Png = ImageUi.GetImage("3") },
                        new CuiRectTransformComponent { AnchorMin = "0 0.5", AnchorMax = "0 0.5", Offs
// ... [Code preview truncated due to length. Full source in attached file] ...

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

Другие ресурсы пользователя 15FPS

Сверху