C#:
using Oxide.Game.Rust.Cui;
using UnityEngine.Networking;
using System.Text.RegularExpressions;
using System.Text;
using System;
using Object = System.Object;
using Oxide.Core.Libraries.Covalence;
using System.Collections;
using Oxide.Core.Plugins;
using System.Collections.Generic;
using Oxide.Core.Database;
using Oxide.Core;
using UnityEngine;
using ConVar;
using System.Linq;
using Newtonsoft.Json;
namespace Oxide.Plugins {
[Info("IQEconomic", "fix", "1.25.30")]
[Description("Экономика на ваш сервер")]
class IQEconomic : RustPlugin {
private Double TimeUnblockExchange(Int32 TimeExchange) => (SaveRestore.SaveCreatedTime.ToUniversalTime().Subtract(epoch).TotalSeconds + TimeExchange) - CurrentTime;
private Configuration.TransferSetting.ExchangeRate GetExcahngeRate() {
Configuration.TransferSetting.ExchangeRate rate = null;
foreach (KeyValuePair<Int32, Configuration.TransferSetting.ExchangeRate> exchangeRate in config.TransferSettings.ExchangeRates.OrderByDescending(x => x.Key)) if (TimeUnblockExchange(exchangeRate.Key) <= 0) {
rate = exchangeRate.Value;
break;
}
return rate;
}
private readonly Core.MySql.Libraries.MySql sqlLibrary = Interface.Oxide.GetLibrary<Core.MySql.Libraries.MySql>();
private static string HexToRustFormat(string hex) {
Color color;
ColorUtility.TryParseHtmlString(hex, out color);
return string.Format("{0:F2} {1:F2} {2:F2} {3:F2}", color.r, color.g, color.b, color.a);
}
int API_GET_BALANCE(string userID) => GetBalance(ulong.Parse(userID));
void API_SET_BALANCE(string userID, int Balance, ItemContainer itemContainer = null) => SetBalance(ulong.Parse(userID), Balance, itemContainer);
public bool IsClans(string userID, string targetID) {
if (Clans) {
if(Clans.Author.Contains("dcode")) {
String TagUserID = (String)Clans?.Call("GetClanOf", userID);
String TagTargetID = (String)Clans?.Call("GetClanOf", targetID);
return (bool)(TagUserID == TagTargetID);
}
else return (bool)Clans?.Call("IsClanMember", userID, targetID);
}
else return false;
}
private String SQL_Query_CreatedDatabase() {
String CreatedDB = $"CREATE TABLE IF NOT EXISTS `{(String.IsNullOrWhiteSpace(config.MySQLConnectionSettings.DataBaseNameTable) ? "DataPlayers" : config.MySQLConnectionSettings.DataBaseNameTable)}`(" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`steamid` VARCHAR(255) NOT NULL," + "`balance` VARCHAR(255) NOT NULL," + "`limit_balance` VARCHAR(255) NOT NULL," + "`time` VARCHAR(255) NOT NULL," + "`last_connection` VARCHAR(255) NOT NULL," + " PRIMARY KEY(`id`))";
return CreatedDB;
}
public void TransferPlayer(ulong userID, ulong transferUserID, int Balance ) {
BasePlayer player = BasePlayer.FindByID(userID);
BasePlayer transferPlayer = BasePlayer.FindByID(transferUserID);
if (player == null) return;
if (transferPlayer == null) return;
if (!IsRemoveBalance(player.userID.Get(), Balance)) {
SendChat(GetLang("BALANCE_TRANSFER_NO_BALANCE", player.UserIDString), player);
return;
}
RemoveBalance(player.userID.Get(), Balance);
SetBalance(transferPlayer.userID.Get(), Balance);
SendChat(GetLang("BALANCE_TRANSFER_PLAYER", player.UserIDString, transferPlayer.displayName, Balance), player);
SendChat(GetLang("BALANCE_TRANSFER_TRANSFERPLAYER", transferPlayer.UserIDString, Balance, player.displayName), transferPlayer);
}
void API_TRANSFERS(ulong userID, ulong trasferUserID, int Balance) => TransferPlayer(userID, trasferUserID, Balance);
private class PlayerInfo : SplitDatafile<PlayerInfo> {
private const String BaseFolder = "IQSystem" + "/" + "IQEconomic" + "/";
public static PlayerInfo Save(String id) => Save(BaseFolder, id);
public static void Import(String id, PlayerInfo data) => Import(BaseFolder, id, data);
public static void Remove(String id) => Remove(BaseFolder, id);
public static PlayerInfo Get(String id) => Get(BaseFolder, id);
public static PlayerInfo Load(String id) => Load(BaseFolder, id);
public static PlayerInfo Clear(String id) => ClearAndSave(BaseFolder, id);
public static PlayerInfo GetOrLoad(String id) => GetOrLoad(BaseFolder, id);
public static PlayerInfo GetOrCreate(String id) => GetOrCreate(BaseFolder, id);
public static String[] GetFiles() => GetFiles(BaseFolder);
[JsonProperty(LanguageEn ? "Player Balance" : "Баланс игрока")]
public Int32 Balance;
[JsonProperty(LanguageEn ? "Player's balance withdrawal limit" : "Лимит вывода баланса игрока")]
public Int32 LimitBalance;
[JsonProperty(LanguageEn ? "Time counter" : "Счетчик времени")]
public Int32 Time;
[JsonProperty(LanguageEn ? "The player's last login to the server" : "Последний вход игрока на сервер")]
public Double DateTime;
}
[JsonProperty(LanguageEn ? "The time of the current time for the withdrawal limit" : "Время действующего времени на лимит выводов")]
public Int32 ActualityLimitTime;
private void ValidatePlayerDatabase(String UserID) {
if (sqlConnection == null) return;
Sql sql = Sql.Builder.Append(SQL_Query_SelectedDatabase(UserID));
sqlLibrary.Query(sql, sqlConnection, list => {
if (list.Count > 0) foreach (Dictionary<String, Object> entry in list) {
String SteamID = (String)entry["steamid"];
if (!SteamID.IsSteamId()) return;
if (!Int32.TryParse((String)entry["balance"], out Int32 Balance)) return;
if (!Int32.TryParse((String)entry["limit_balance"], out Int32 LimitBalance)) return;
if (!Int32.TryParse((String)entry["time"], out Int32 Time)) return;
if (!Double.TryParse((String)entry["last_connection"], out Double DateTime)) return;
RegisteredDataUserFromMySQL(SteamID, Balance, LimitBalance, Time, DateTime);
}
}
);
}
void API_TRANSFERS(BasePlayer player, string trasferUserID, int Balance) => TransferPlayer(player.userID.Get(), ulong.Parse(trasferUserID), Balance);
[ConsoleCommand("transfer.all")]
void TransferAll(ConsoleSystem.Arg args) {
BasePlayer player = args.Player();
if (player == null) return;
if (CooldownTransfer.ContainsKey(player)) {
if (CooldownTransfer[player] > CurrentTime) return;
CooldownTransfer[player] = CurrentTime + 2f;
}
else CooldownTransfer.Add(player, CurrentTime + 2f);
Int32 Balance = config.TransferSettings.UseLimits ? GetBalance(player.userID.Get()) > GetLimit(player.UserIDString) ? GetLimit(player.UserIDString) : GetBalance(player.userID.Get()) : GetBalance(player.userID.Get());
Configuration.TransferSetting.ExchangeRate Transfer = GetExcahngeRate();
if (Transfer == null) {
SendChat(GetLang("UI_NO_EXCANCHGE", player.UserIDString), player);
return;
}
if (!IsTransfer(Balance, Transfer.MoneyCount)) return;
UpdateButtonEchange(player, true);
var Reference = config.ReferenceSettings;
Int32 ResultTakeMoney = Balance / Transfer.MoneyCount * Transfer.StoresMoneyCount;
Int32 remainder = Balance % Transfer.MoneyCount;
if (remainder != 0) {
Balance -= remainder;
ResultTakeMoney = Balance / Transfer.MoneyCount * Transfer.StoresMoneyCount;
}
if (Reference.GameStoreshUse) GameStoresBalanceSet(player.userID.Get(), ResultTakeMoney, Balance);
if (Reference.MoscovOvhUse) MoscovOVHBalanceSet(player.userID.Get(), ResultTakeMoney, Balance);
if (config.TransferSettings.UseLimits) LimitedUpdate(player.UserIDString, Balance);
}
public void RemoveBalance(BasePlayer player, int removeBalance) {
if (player == null) {
PrintWarning(GetLang("BALANCE_CUSTOM_MONEY_NOT_PLAYER"));
return;
}
if(!IsRemoveBalance(player, removeBalance)) {
PrintWarning(GetLang("BALANCE_CUSTOM_MONEY_NO_COUNT_TAKE"));
return;
}
if (!config.UseUI) {
TakeItems(player, removeBalance);
//TakeMoneyPlayer(player, removeBalance);
}
else {
String playerID = player.UserIDString;
PlayerInfo playerData = PlayerInfo.Get(playerID);
if (playerData != null) {
playerData.Balance -= removeBalance;
if (config.ShowUI) Interface_Balance(player);
}
else RegisteredDataUser(playerID);
if (config.MySQLConnectionSettings.UseMySQL) InserDatabase(player.UserIDString, playerData.Balance, playerData.LimitBalance, playerData.Time, playerData.DateTime);
}
Interface.Oxide.CallHook("SET_BALANCE_USER", player.userID.Get(), removeBalance);
}
void API_SET_BALANCE(BasePlayer player, int Balance, ItemContainer itemContainer = null) => SetBalance(player, Balance, itemContainer);
private void OnLootSpawn(LootContainer container) {
if (container == null || !config.GeneralSetting.SettingDropMoneyPreset.Presets.ContainsKey(container.ShortPrefabName)) return;
Configuration.GeneralSettings.SettingDropMoney.Preset preset = config.GeneralSetting.SettingDropMoneyPreset.Presets[container.ShortPrefabName];
if (!IsRare(preset.Rare)) return;
timer.In(0.21f, () => {
if (container.inventory == null) return;
Int32 RandomMoney = UnityEngine.Random.Range(preset.MoneyMin, preset.MoneyMax);
if (container.inventory.capacity <= container.inventory.itemList.Count) container.inventory.capacity = container.inventory.itemList.Count + 1;
Item item = config?.CustomMoneySetting?.ToItem(RandomMoney);
if (item == null) return;
item.MoveToContainer(container.inventory);
}
);
}
private Tuple<Int32, Configuration.TransferSetting.ExchangeRate> GetNextExchangeRateKey() {
var orderedExchangeRates = config.TransferSettings.ExchangeRates.OrderBy(x => x.Key).ToList();
int currentIndex = orderedExchangeRates.FindIndex(x => LastLocalExchangeRate == x.Value);
if (currentIndex == -1 || currentIndex == orderedExchangeRates.Count - 1) {
return new Tuple<Int32, Configuration.TransferSetting.ExchangeRate>(-1, null);
}
KeyValuePair<Int32, Configuration.TransferSetting.ExchangeRate> nextPair = orderedExchangeRates[currentIndex + 1];
return Tuple.Create(nextPair.Key, nextPair.Value);
}
bool API_MONEY_TYPE() => (!config.UseUI);
void ChatCommandBalance(BasePlayer player) {
SendChat(GetLang("CHAT_MY_BALANCE", player.UserIDString, GetBalance(player.userID.Get())), player);
}
public void RemoveBalance(ulong userID, int removeBalance) {
BasePlayer player = BasePlayer.FindByID(userID);
if (player == null) {
PrintWarning(GetLang("BALANCE_CUSTOM_MONEY_NOT_PLAYER"));
return;
}
RemoveBalance(player, removeBalance);
}
void API_REMOVE_BALANCE(string userID, int Balance) => RemoveBalance(ulong.Parse(userID), Balance);
void API_SET_BALANCE(ulong userID, int Balance, ItemContainer itemContainer = null) => SetBalance(userID, Balance, itemContainer);
bool API_IS_REMOVED_BALANCE(ulong userID, int Amount) => IsRemoveBalance(userID, Amount);
protected override void LoadDefaultConfig() => config = Configuration.GetNewConfiguration();
public String FormatTime(TimeSpan time, String UserID) {
String Result = String.Empty;
String Days = GetLang("TITLE_FORMAT_LOCKED_DAYS", UserID);
String Hourse = GetLang("TITLE_FORMAT_LOCKED_HOURSE", UserID);
String Minutes = GetLang("TITLE_FORMAT_LOCKED_MINUTES", UserID);
String Seconds = GetLang("TITLE_FORMAT_LOCKED_SECONDS", UserID);
if (time.Days != 0) Result += $"{Format(time.Days, Days, Days, Days)}";
if (time.Hours != 0) Result += $" {Format(time.Hours, Hourse, Hourse, Hourse)}";
if (time.Minutes != 0) Result += $" {Format(time.Minutes, Minutes, Minutes, Minutes)}";
if (time.Days == 0 && time.Hours == 0 && time.Minutes == 0 && time.Seconds != 0) Result = $" {Format(time.Seconds, Seconds, Seconds, Seconds)}";
return Result;
}
private void SQL_OpenConnection() {
Configuration.MySQLConnection SQLInfo = config.MySQLConnectionSettings;
if (!SQLInfo.UseMySQL) return;
if (String.IsNullOrWhiteSpace(SQLInfo.IP) || String.IsNullOrWhiteSpace(SQLInfo.Password) || String.IsNullOrWhiteSpace(SQLInfo.Port) || String.IsNullOrWhiteSpace(SQLInfo.DataBaseName) || String.IsNullOrWhiteSpace(SQLInfo.UserName)) {
PrintError(LanguageEn ? "You have MySQL support enabled but fixed to make SQL work correctly!" : "У вас включена поддержка MySQL но некоторые поля пустые, исправьте чтобы SQL работал корректно!");
return;
}
sqlConnection = sqlLibrary.OpenDb(SQLInfo.IP, Convert.ToInt32(SQLInfo.Port), SQLInfo.DataBaseName, SQLInfo.UserName, SQLInfo.Password, this);
if (sqlConnection == null) return;
Sql sql = Sql.Builder.Append(SQL_Query_CreatedDatabase());
sqlLibrary.Insert(sql, sqlConnection);
sql = Sql.Builder.Append(SQL_Query_SelectedDatabase());
sqlLibrary.Query(sql, sqlConnection, list => {
if (list.Count > 0) foreach (Dictionary<String, Object> entry in list) {
String SteamID = (String)entry["steamid"];
if (!SteamID.IsSteamId()) {
PrintError(LanguageEn ? "Error parsing SteamID player" : "Ошибка парсинга SteamID игрока");
return;
}
Int32 Balance = 0;
if (!Int32.TryParse((String)entry["balance"], out Balance)) {
PrintError(LanguageEn ? "Error parsing Balance player" : "Ошибка парсинга Balance игрока");
return;
}
Int32 LimitBalance = 0;
if (!Int32.TryParse((String)entry["limit_balance"], out LimitBalance)) {
PrintError(LanguageEn ? "Error parsing LimitBalance player" : "Ошибка парсинга LimitBalance игрока");
return;
}
Int32 Time = 0;
if (!Int32.TryParse((String)entry["time"], out Time)) {
PrintError(LanguageEn ? "Error parsing Time player" : "Ошибка парсинга Time игрока");
return;
}
Double DateTime = 0;
if (!Double.TryParse((String)entry["last_connection"], out DateTime)) {
PrintError(LanguageEn ? "Error parsing DateTime player" : "Ошибка парсинга DateTime игрока");
return;
}
RegisteredDataUserFromMySQL(SteamID, Balance, LimitBalance, Time, DateTime);
}
PrintWarning(LanguageEn ? "Updated information about users from the database" : "Обновлена информация о пользователях из БД");
foreach (BasePlayer player in BasePlayer.activePlayerList) OnPlayerConnected(player);
}
);
}
enum TypeData {
None, AllWipe, AllWipeOnlyBalance, TimeClear, TimeClearOnlyBalance,
}
public Boolean IsLimited(String playerID, Int32 Amount) {
if (config.TransferSettings.UseLimits) return GetLimit(playerID) < Amount;
else return false;
}
void RegisteredDataUser(String playerID) {
if (!playerID.IsSteamId()) return;
PlayerInfo playerData = PlayerInfo.Get(playerID);
if (playerData == null) PlayerInfo.Import(playerID, new PlayerInfo {
Balance = config.StartedBalance, LimitBalance = config.TransferSettings.LimitBalance, Time = 0, DateTime = CurrentTime
}
);
else playerData.DateTime = CurrentTime;
}
private void OnServerInitialized() {
PlayerInfo._players = new Dictionary<String, PlayerInfo>();
_imageUI = new ImageUI();
_imageUI.DownloadImage();
cmd.AddChatCommand(config.ChatCommandBalance, this, nameof(ChatCommandBalance));
permission.RegisterPermission(config.GeneralSetting.TimeReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.NPCReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.KilledReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.HelicopterReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.GatherReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.CollectableReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.BradleyReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.BarrelReward.PermissionReward, this);
permission.RegisterPermission(config.GeneralSetting.AnimalReward.PermissionReward, this);
if (config.MySQLConnectionSettings.UseMySQL) SQL_OpenConnection();
else {
LoadDataFiles();
if (Oxide.Core.Interface.Oxide.DataFileSystem.ExistsDatafile("IQEconomic/DataEconomics")) {
Int32 count = 0;
DataEconomics = Oxide.Core.Interface.Oxide.DataFileSystem.ReadObject<Dictionary<UInt64, InformationData>>("IQEconomic/DataEconomics");
foreach (KeyValuePair<UInt64, InformationData> oldData in DataEconomics) {
PlayerInfo.Import(oldData.Key.ToString(), new PlayerInfo {
Balance = oldData.Value.Balance, LimitBalance = oldData.Value.LimitBalance, Time = oldData.Value.Time, DateTime = oldData.Value.DateTime
}
);
count++;
}
PrintWarning($"Перенесено {count} игроков из старого дата-файла");
SaveDataFiles();
Oxide.Core.Interface.Oxide.DataFileSystem.DeleteDataFile("IQEconomic/DataEconomics");
LoadDataFiles();
}
if(isNewSave) ClearDataFile();
foreach (BasePlayer player in BasePlayer.activePlayerList) OnPlayerConnected(player);
}
LastLocalExchangeRate = GetExcahngeRate();
if (config.GeneralSetting.TimeReward.UseReward) timer.Every(120f, TrackerTime);
if(!config.MySQLConnectionSettings.UseMySQL || sqlConnection == null) if (config.GeneralSetting.DataFileSetting.SaveTime > 0) timer.Every(config.GeneralSetting.DataFileSetting.SaveTime, SaveDataFiles);
if (config.TransferSettings.UseAlertExchangeNew) timer.Every(300f, RefreshExchnage);
ResetLimit();
if (config.GeneralSetting.SettingDropMoneyPreset.UseDropMoney && !config.UseUI) Subscribe("OnLootSpawn");
if (!config.useSaveMoneyForDeath || config.UseUI) {
Unsubscribe("OnPlayerDeath");
Unsubscribe("OnPlayerRespawned");
}
}
private Connection sqlConnection = null;
private void RefreshExchnage() {
Configuration.TransferSetting.ExchangeRate RefreshRate = GetExcahngeRate();
if (LastLocalExchangeRate != null && LastLocalExchangeRate != RefreshRate) {
LastLocalExchangeRate = RefreshRate;
foreach (BasePlayer player in BasePlayer.activePlayerList) SendChat(GetLang("UI_NEW_EXCHANGE_RATE", player.UserIDString), player);
}
}
void Unload() {
if (_ == null) return;
foreach(BasePlayer player in BasePlayer.activePlayerList) {
CuiHelper.DestroyUi(player, UI_BALANCE_PARENT);
CuiHelper.DestroyUi(player, UI_CHANGER_PARENT);
}
if (!config.MySQLConnectionSettings.UseMySQL) SaveDataFiles();
PlayerInfo._players.Clear();
PlayerInfo._players = null;
if (coroutineMigrate != null) coroutineMigrate = null;
if (sqlConnection != null) sqlLibrary?.CloseDb(sqlConnection);
if (_imageUI != null) {
_imageUI.UnloadImages();
_imageUI = null;
}
Oxide.Core.Interface.Oxide.DataFileSystem.WriteObject("IQSystem/IQEconomic/Limits/ActualityLimitTime", ActualityLimitTime);
_ = null;
}
public bool IsRemoveBalance(BasePlayer player, int Amount) => (GetBalance(player) >= Amount);
public void MoscovOVHBalanceSet(ulong userID, int Balance) {
if (!RustStore) {
PrintWarning("У вас не установлен магазин MoscovOVH");
return;
}
plugins.Find("RustStore").CallHook("APIChangeUserBalance", userID, Balance, new Action<string>((result) => {
BasePlayer player = BasePlayer.FindByID(userID);
if (result == "SUCCESS") {
Puts($"Пользователю {userID} успешно зачислен баланс - {Balance}");
if (player == null) return;
// SendChat(GetLang("CHAT_STORE_SUCCESS", player.UserIDString), player);
return;
}
Puts($"Пользователь {userID} не авторизован в магазине");
if (player == null) return;
SendChat(GetLang("CHAT_NO_AUTH_STORE", player.UserIDString), player);
}
));
}
private void OnPlayerRespawned(BasePlayer player) {
if (!moneyAmountSavePlayer.ContainsKey(player)) return;
SetBalance(player, moneyAmountSavePlayer[player], isSave : true);
moneyAmountSavePlayer.Remove(player);
}
private void TakeItems(BasePlayer player, Int32 TargetAmount = 1) {
List<Item> acceptedItems = GetAcceptedItems(player);
foreach (Item use in acceptedItems) {
if (use.amount == TargetAmount) {
use.RemoveFromContainer();
use.Remove();
TargetAmount = 0;
break;
}
if (use.amount > TargetAmount) {
use.amount -= TargetAmount;
player.inventory.SendSnapshot();
TargetAmount = 0;
break;
}
if (use.amount < TargetAmount) {
TargetAmount -= use.amount;
use.RemoveFromContainer();
use.Remove();
}
}
}
void API_TRANSFERS(BasePlayer player, ulong trasferUserID, int Balance) => TransferPlayer(player.userID.Get(), trasferUserID, Balance);
private void OnServerShutdown() => Unload();
protected override void LoadConfig() {
base.LoadConfig();
try {
config = Config.ReadObject<Configuration>();
if (config == null) LoadDefaultConfig();
if (config.ChatCommandBalance == null || String.IsNullOrEmpty(config.ChatCommandBalance)) config.ChatCommandBalance = "balance";
if (config.TransferSettings.ExchangeRates == null || config.TransferSettings.ExchangeRates.Count == 0) {
config.TransferSettings.ExchangeRates = new Dictionary<Int32, Configuration.TransferSetting.ExchangeRate>() {
[0]
= new Configuration.TransferSetting.ExchangeRate() {
MoneyCount = 3, StoresMoneyCount = 1
}
, [86400] = new Configuration.TransferSetting.ExchangeRate() {
MoneyCount = 4, StoresMoneyCount = 1
}
, [172800] = new Configuration.TransferSetting.ExchangeRate() {
MoneyCount = 5, StoresMoneyCount = 1
}
, [259200] = new Configuration.TransferSetting.ExchangeRate() {
MoneyCount = 6, StoresMoneyCount = 1
}
, [345600] = new Configuration.TransferSetting.ExchangeRate() {
MoneyCount = 8, StoresMoneyCount = 2
}
,
}
;
}
if (config.GeneralSetting.SettingDropMoneyPreset == null) config.GeneralSetting.SettingDropMoneyPreset = new Configuration.GeneralSettings.SettingDropMoney() {
UseDropMoney = false, Presets = new Dictionary<String, Configuration.GeneralSettings.SettingDropMoney.Preset>() {
["crate_elite"]
= new Configuration.GeneralSettings.SettingDropMoney.Preset() {
Rare = 100, MoneyMin = 3, MoneyMax = 5
}
, ["crate_normal"] = new Configuration.GeneralSettings.SettingDropMoney.Preset() {
Rare = 10, MoneyMin = 30, MoneyMax = 50
}
,
}
}
;
if (config.GeneralSetting.SettingDropMoneyPreset.Presets == null || config.GeneralSetting.SettingDropMoneyPreset.Presets.Count == 0) {
config.GeneralSetting.SettingDropMoneyPreset.Presets = new Dictionary<String, Configuration.GeneralSettings.SettingDropMoney.Preset>() {
["crate_elite"]
= new Configuration.GeneralSettings.SettingDropMoney.Preset() {
Rare = 100, MoneyMin = 3, MoneyMax = 5
}
, ["crate_normal"] = new Configuration.GeneralSettings.SettingDropMoney.Preset() {
Rare = 10, MoneyMin = 30, MoneyMax = 50
}
,
}
;
}
}
catch {
PrintWarning(LanguageEn ? "Error #49" + $"reading the configuration 'oxide/config/{Name}', creating a new configuration! #33" : "Ошибка #49" + $"чтения конфигурации 'oxide/config/{Name}', создаём новую конфигурацию! #33");
LoadDefaultConfig();
}
NextTick(SaveConfig);
}
public static string UI_BALANCE_PARENT = "BALANCE_PLAYER_PARENT";
bool API_IS_USER(ulong userID) => API_IS_USER(userID.ToString());
private Dictionary<BasePlayer, Int32> moneyAmountSavePlayer = new();
string API_GET_STORES_IL() {
return "URLStores";
}
public bool IsTransfer(int Balance, Int32 MoneyCount) {
if (Balance <= 0) return false;
if (Balance >= MoneyCount) return true;
else return false;
}
void OnEntityDeath(BaseCombatEntity entity, HitInfo info) {
if (entity == null || info == null) return;
BasePlayer player = info.InitiatorPlayer;
if (info.InitiatorPlayer == null && entity as PatrolHelicopter) player = BasePlayer.FindByID(GetLastAttacker(entity.net.ID.Value));
if (player == null) return;
Configuration.GeneralSettings General = config.GeneralSetting;
Configuration.ReferenceSetting ReferenceGeneral = config.ReferenceSettings;
Boolean isPlayer = entity is BasePlayer;
Boolean isNPC = (entity is NPCPlayer || entity.IsNpc || entity is BaseNpc) && entity is not BaseAnimalNPC;
Boolean isAnimal = entity is BaseAnimalNPC;
Boolean isHelicopter = entity is PatrolHelicopter;
Boolean isBradley = entity is BradleyAPC;
Boolean isBarrel = entity.PrefabName.Contains("barrel") && !entity.PrefabName.Contains("hobobarrel");
if (isNPC) {
if (IQSphereEvent) {
TierIQSphereEvent TierNPC = GetTierIQSphereEvent(entity.OwnerID);
if (General.IQSphereNpcReward.TryGetValue(TierNPC, out Configuration.GeneralSettings.GeneralSettingReward NPCReward) && NPCReward != null) {
if (!String.IsNullOrWhiteSpace(NPCReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, NPCReward.PermissionReward)) return;
if (IsRare(NPCReward.AdvancedReward.Rare)) SetBalance(player.userID.Get(), NPCReward.AdvancedReward.Money);
return;
}
}
if (General.NPCReward.UseReward) {
Configuration.GeneralSettings.AdvancedSetting Setting = General.NPCReward.AdvancedReward;
if (!String.IsNullOrWhiteSpace(General.NPCReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, General.NPCReward.PermissionReward)) return;
if (IsRare(Setting.Rare)) SetBalance(player.userID.Get(), Setting.Money);
return;
}
}
if (isPlayer && entity.ToPlayer() != null && player.userID.Get() != entity.ToPlayer().userID.Get()) {
if (General.KilledReward.UseReward) {
if (!String.IsNullOrWhiteSpace(General.KilledReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, General.KilledReward.PermissionReward)) return;
if (ReferenceGeneral.FriendsBlockUse && IsFriends(player.userID.Get(), entity.ToPlayer().userID.Get())) return;
if (ReferenceGeneral.ClansBlockUse && IsClans(player.UserIDString, entity.ToPlayer()?.UserIDString)) return;
if (ReferenceGeneral.DuelBlockUse && IsDuel(player.userID.Get())) return;
Configuration.GeneralSettings.AdvancedSetting Setting = General.KilledReward.AdvancedReward;
if (IsRare(Setting.Rare)) SetBalance(player.userID.Get(), Setting.Money);
return;
}
}
if (isAnimal && General.AnimalReward.UseReward) {
Configuration.GeneralSettings.AdvancedSetting Setting = General.AnimalReward.AdvancedReward;
if (!String.IsNullOrWhiteSpace(General.AnimalReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, General.AnimalReward.PermissionReward)) return;
if (IsRare(Setting.Rare)) SetBalance(player.userID.Get(), Setting.Money);
return;
}
if (isHelicopter && General.HelicopterReward.UseReward) {
Configuration.GeneralSettings.AdvancedSetting Setting = General.HelicopterReward.AdvancedReward;
if (!String.IsNullOrWhiteSpace(General.HelicopterReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, General.HelicopterReward.PermissionReward)) return;
if (IsRare(Setting.Rare)) SetBalance(player.userID.Get(), Setting.Money);
return;
}
if (isBradley && General.BradleyReward.UseReward) {
Configuration.GeneralSettings.AdvancedSetting Setting = General.BradleyReward.AdvancedReward;
if (!String.IsNullOrWhiteSpace(General.BradleyReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, General.BradleyReward.PermissionReward)) return;
if (IsRare(Setting.Rare)) SetBalance(player.userID.Get(), Setting.Money);
return;
}
if (isBarrel && General.BarrelReward.UseReward) {
Configuration.GeneralSettings.AdvancedSetting Setting = General.BarrelReward.AdvancedReward;
if (!String.IsNullOrWhiteSpace(General.BarrelReward.PermissionReward) && !permission.UserHasPermission(player.UserIDString, General.BarrelReward.PermissionReward)) return;
if (IsRare(Setting.Rare)) SetBalance(player.userID.Get(), Setting.Money);
}
}
private void ResetLimit() {
if (!config.TransferSettings.UseLimits) return;
timer.Once(300f, ResetLimit);
if (ActualityLimitTime > CurrentTime) return;
ActualityLimitTime = Convert.ToInt32(CurrentTime + config.TransferSettings.LimitTime);
foreach (PlayerInfo Value in PlayerInfo._players.Values) NextTick(() => {
Value.LimitBalance = config.TransferSettings.LimitBalance;
}
);
Puts(LanguageEn ? "The balance limit has been reset for the time elapsed" : "Лимит баланса был сброшен за пройденное время");
}
public class GameStoresConfiguration {
public class API {
[JsonProperty("Секретный ключ (не распространяйте его)")]
public string SecretKey;
[JsonProperty("ИД магазина в сервисе")]
public string ShopID;
}
[JsonProperty("Настройки API плагина")]
public API APISettings;
}
private void InserDatabase(String UserID, Int32 Balance, Int32 LimitBalance, Int32 Time, Double DateTime, Boolean IsMigrate = false) {
if (sqlConnection == null) return;
String sqlQuery = $"UPDATE {(String.IsNullOrWhiteSpace(config.MySQLConnectionSettings.DataBaseNameTable) ? "DataPlayers" : config.MySQLConnectionSettings.DataBaseNameTable)} SET `steamid` = @0, `balance` = @1,`limit_balance` = @2,`time` = @3,`last_connection` = @4 WHERE `steamid` = @0";
Sql updateCommand = Oxide.Core.Database.Sql.Builder.Append(sqlQuery, UserID, Balance, LimitBalance, Time, DateTime);
sqlLibrary.Update(updateCommand, sqlConnection, rowsAffected => {
if (rowsAffected <= 0) {
String Query = String.Format(SQL_Query_InsertUser(), UserID, Balance, LimitBalance, Time, DateTime);
Sql sql = Sql.Builder.Append(Query);
sqlLibrary.Insert(sql, sqlConnection, rowsAffecteds => {
if (!IsMigrate) Puts(LanguageEn? "A new user has been added to the database" : "В БД был внесен новый пользователь");
}
);
}
}
);
}
void RegisteredDataUserFromMySQL(String playerID, Int32 Balance, Int32 LimitBalance, Int32 Time, Double DateTime) {
if (!playerID.IsSteamId()) return;
PlayerInfo playerData = PlayerInfo.Get(playerID);
if (playerData == null) {
PlayerInfo.Import(playerID, new PlayerInfo {
Balance = Balance, LimitBalance = LimitBalance, Time = Time, DateTime = DateTime
}
);
}
else {
playerData.Balance = Balance;
playerData.LimitBalance = LimitBalance;
playerData.Time = Time;
playerData.DateTime = DateTime;
}
}
void API_TRANSFERS(ulong userID, string trasferUserID, int Balance) => TransferPlayer(userID, ulong.Parse(trasferUserID), Balance);
private Dictionary<BasePlayer, Double> CooldownTransfer = new Dictionary<BasePlayer, Double>();
private Boolean isNewSave = false;
private void TrackerTime() {
Configuration.GeneralSettings.TimeSettingsReward TimeSetting = config.GeneralSetting.TimeReward;
IEnumerable<BasePlayer> FiltredList = !String.IsNullOrWhiteSpace(TimeSetting.PermissionReward) ? BasePlayer.activePlayerList.Where(x => permission.UserHasPermission(x.UserIDString, TimeSetting.PermissionReward)) : BasePlayer.activePlayerList;
foreach (BasePlayer player in FiltredList) {
PlayerInfo playerData = PlayerInfo.Get(player.UserIDString);
if (playerData == null) {
PrintWarning("Null P");
continue;
}
if (playerData.Time <= CurrentTime) {
Int32 SetTime = Convert.ToInt32(config.GeneralSetting.TimeReward.OnlineTime + CurrentTime);
SetBalance(player.userID.Get(), config.GeneralSetting.TimeReward.OnlineTimeReward);
playerData.Time = SetTime;
}
}
}
public void Interface_Balance(BasePlayer player) {
CuiElementContainer container = new CuiElementContainer();
CuiHelper.DestroyUi(player, UI_BALANCE_PARENT);
var Balance = GetBalance(player.userID.Get());
Configuration.Interface Interface = config.InterfaceSetting;
container.Add(new CuiPanel {
RectTransform = {
AnchorMin = Interface.AnchorMin, AnchorMax = Interface.AnchorMax, OffsetMin = Interface.OffsetMin, OffsetMax = Interface.OffsetMax
}
, Image = {
FadeIn = 0.15f, Color = HexToRustFormat(Interface.ColorBackground), Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat"
}
}
, "Hud", UI_BALANCE_PARENT);
container.Add(new CuiPanel {
RectTransform = {
AnchorMin = $"0.01932367 0.04938272", AnchorMax = $"0.154153463 0.93823463"
}
, Image = {
FadeIn = 0.15f, Color = HexToRustFormat(Interface.ColorMoreOne), Sprite = "assets/icons/connection.png"
}
}
, UI_BALANCE_PARENT);
container.Add(new CuiPanel {
RectTransform = {
AnchorMin = $"0.1835208 0.1358024", AnchorMax = $"0.9625472 0.8518519"
}
, Image = {
FadeIn = 0.15f, Color = HexToRustFormat(Interface.ColorMoreTwo), Material = "assets/content/ui/uibackgroundblur-ingamemenu.mat"
}
}
, UI_BALANCE_PARENT);
container.Add(new CuiLabel {
RectTransform = {
AnchorMin = "0.22 0", AnchorMax = "1 1"
}
, Text = {
Text = GetLang("UI_MY_BALANCE", player.UserIDString, Balance), Color = HexToRustFormat(Interface.ColorLabel), Font = "robotocondensed-bold.ttf", Align = TextAnchor.MiddleLeft, FadeIn = 0.3f
}
}
, UI_BALANCE_PARENT);
CuiHelper.AddUi(player, container);
}
private class Configuration {
[JsonProperty(LanguageEn ? "Chat command to view balance" : "Чат команда для просмотра баланса")]
public String ChatCommandBalance;
[JsonProperty(LanguageEn ? "Keep player coins after death? (They will be removed from the corpse)" : "Сохранять монеты игрока после его смерти? (из трупа будут удалены)")]
public Boolean useSaveMoneyForDeath;
[JsonProperty(LanguageEn ? "The coins will be in the form of an item - false / Otherwise there will be a chat or interface - true" : "Монетки будут и гроков на руках - false / Иначе будет чат или интерфейсе - true")]
public Boolean UseUI;
[JsonProperty(LanguageEn ? "Use the UI interface to display the balance (true - yes (If you did not put the coins in item))/false - the information will be in the chat on command and at the entrance)" : "Использовать UI интерфейс для отображения баланса(true - да(Если вы не поставили , чтобы монетки были на руках))/false - информация будет в чате по команде и при входе)")]
public Boolean UseUIMoney;
[JsonProperty(LanguageEn ? "Displaying the interface with a balance (true - displays/false - hides)" : "Отображение интерфейса с балансом(true - отображает/false - скрывает)")]
public Boolean ShowUI;
[JsonProperty(LanguageEn ? "Enable notifications to the player about receiving currency for mining (true - yes/false - no)" : "Включить уведомления игроку о получении валюты за добычу (true - да/false - нет)")]
public Boolean UseAlert = true;
[JsonProperty(LanguageEn ? "Starting balance for all players" : "Стартовый баланс для всех игроков")]
public Int32 StartedBalance = 0;
[JsonProperty(LanguageEn ? "Interface settings in the plugin (Do not touch if you do not understand how to work with it)" : "Настройки интерфейса в плагине (Не трогайте, если не понимаете как с этим работать)")]
public Interface InterfaceSetting = new Interface();
[JsonProperty(LanguageEn ? "Currency exchange settings for the balance in the store" : "Настройки обмена валют на баланс в магазине")]
public TransferSetting TransferSettings = new TransferSetting();
[JsonProperty(LanguageEn ? "Basic Settings" : "Основные настройки")]
public GeneralSettings GeneralSetting = new GeneralSettings();
[JsonProperty(LanguageEn ? "Currency settings (If the type of coins in item)" : "Настройки валюты(Если вид экономики - false)")]
public CustomMoney CustomMoneySetting = new CustomMoney();
[JsonProperty(LanguageEn ? "Settings for collaboration with other plugins" : "Настройки совместной работы с другими плагинами")]
public ReferenceSetting ReferenceSettings = new ReferenceSetting();
[JsonProperty(LanguageEn ? "MySQL connection settings" : "Настройки соединения с MySQL")]
public MySQLConnection MySQLConnectionSettings = new MySQLConnection();
internal class MySQLConnection {
[JsonProperty(LanguageEn ? "Use MySQL instead of a data file (true - yes/false - no)" : "Использовать MySQL вместо дата-файла (true - да/false - нет)")]
public Boolean UseMySQL;
[JsonProperty("MySQL : Username")]
public String UserName;
[JsonProperty("MySQL : Password")]
public String Password;
[JsonProperty("MySQL : Host(IP)")]
public String IP;
[JsonProperty("MySQL : Port")]
public String Port;
[JsonProperty(LanguageEn ? "MySQL : Name of the database (create it - if it doesn't exist in your database)" : "MySQL : Название базы данных (создайте ее - если ее нет в вашей БД)")]
public String DataBaseName;
[JsonProperty(LanguageEn ? "MySQL : Desired table name in the database" : "MySQL : Желаемое название таблицы в базе данных")]
public String DataBaseNameTable;
}
internal class CustomMoney {
[JsonProperty(LanguageEn ? "Currency name" : "Название валюты")]
public String DisplayName;
[JsonProperty(LanguageEn ? "Coin Shortname" : "Shortname монетки")]
public String Shortname;
[JsonProperty(LanguageEn ? "Coin SkinID" : "SkinID монетки")]
public UInt64 SkinID;
public Item ToItem(Int32 amount = 1) {
var newItem = ItemManager.CreateByName(Shortname, amount, SkinID);
if (newItem == null) {
Debug.LogError($"Error creating item with shortName '{Shortname}'!");
return null;
}
if (!string.IsNullOrEmpty(DisplayName)) newItem.name = DisplayName;
return newItem;
}
}
internal class Interface {
[JsonProperty(LanguageEn ? "Color of the main panel" : "Цвет основной панели")]
public String ColorBackground = "#FFFFFF05";
[JsonProperty(LanguageEn ? "Additional Panel Color #1" : "Цвет дополнительной панели #1")]
public String ColorMoreOne = "#b1b1b1";
[JsonProperty(LanguageEn ? "Additional Panel Color #2" : "Цвет дополнительной панели #2")]
public String ColorMoreTwo = "#CCD045FF";
[JsonProperty(LanguageEn ? "Text color" : "Цвет текста")]
public String ColorLabel = "#FEFFDDFF";
[JsonProperty("AnchorMin")]
public String AnchorMin = "1 0";
[JsonProperty("AnchorMax")]
public String AnchorMax = "1 0";
[JsonProperty("OffsetMin")]
public String OffsetMin = "-390 15";
[JsonProperty("OffsetMax")]
public String OffsetMax = "-212 42";
}
internal class GeneralSettings {
[JsonProperty(LanguageEn ? "Setting up a data file" : "Настройка дата-файла")]
public DataFileSettings DataFileSetting = new DataFileSettings();
internal class DataFileSettings {
[JsonProperty(LanguageEn ? "Save interval file date (Set to 0 if you do not want to save the file by timer)" : "Интервал сохранения дата файла (Установите 0, если не требуется сохранять файл по таймеру)")]
public Int32 SaveTime = 360;
[JsonProperty(LanguageEn ? "Setting up Data file cleanup" : "Настройка очистки дата-файла")]
public DetalisWipeData DetalisWipe = new DetalisWipeData();
internal class DetalisWipeData {
[JsonProperty(LanguageEn ? "Type of data file cleaning : 0 - Do not clean at all, 1 - Clean the entire date when the server is wiped, 2 - Clean the date file of players with a balance of <N (configurable in this category) when the server is wiped, 3 - Clean players who have not logged in >N (configurable in this category) days, 4 - Clear players who have not logged in >N (configurable in this category) days and their balance <N
// ... [Code preview truncated due to length. Full source in attached file] ...