Decompiled source of Valhalla Hungary v1.0.1

BepInEx\plugins\ValhallaCore\ValhallaCore.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace ValhallaServerCore;

[BepInPlugin("hu.valhalla.server.core", "ValhallaCore Master Engine", "1.0.0")]
public class ValhallaCorePlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(Piece), "SetCreator")]
	public static class Patch_Piece_SetCreator
	{
		public static void Postfix(Piece __instance, long creator)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if (!((Object)(object)component == (Object)null) && component.IsValid() && (Object)(object)((Component)__instance).GetComponent<PrivateArea>() != (Object)null)
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && IsAdminPlayer(localPlayer))
				{
					component.GetZDO().Set("Valhalla_AdminWard", true);
					Debug.Log((object)"[ValhallaCore] Admin Védőkő létrehozva! Sérthetetlen godmode és területvédelem aktiválva.");
				}
			}
		}
	}

	[HarmonyPatch(typeof(WearNTear), "Damage")]
	public static class Patch_WearNTear_Damage
	{
		public static bool Prefix(WearNTear __instance, HitData hit)
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || hit == null)
			{
				return true;
			}
			ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
			if ((Object)(object)component != (Object)null && component.IsValid() && component.GetZDO().GetBool("Valhalla_AdminWard", false))
			{
				hit.ApplyModifier(0f);
				hit.m_damage.m_damage = 0f;
				return false;
			}
			if (IsInsideAdminWard(((Component)__instance).transform.position))
			{
				hit.ApplyModifier(0f);
				hit.m_damage.m_damage = 0f;
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(PrivateArea), "CheckAccess")]
	public static class Patch_PrivateArea_CheckAccess
	{
		public static bool Prefix(PrivateArea __instance, Vector3 point, float radius, bool flash, bool wardCheck, ref bool __result)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && IsAdminPlayer(localPlayer))
			{
				__result = true;
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(PrivateArea), "Interact")]
	public static class Patch_PrivateArea_Interact
	{
		public static bool Prefix(PrivateArea __instance, Humanoid human, bool hold, bool alt, ref bool __result)
		{
			Player val = (Player)(object)((human is Player) ? human : null);
			if ((Object)(object)val != (Object)null && IsAdminPlayer(val))
			{
				return true;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	public static class Patch_ZNet_RPC_PeerInfo
	{
		public static bool Prefix(ZNet __instance, ZRpc rpc, ZPackage pkg)
		{
			if ((Object)(object)__instance == (Object)null || !__instance.IsServer())
			{
				return true;
			}
			try
			{
				ZNetPeer val = null;
				List<ZNetPeer> peers = __instance.GetPeers();
				for (int i = 0; i < peers.Count; i++)
				{
					if (peers[i].m_rpc == rpc)
					{
						val = peers[i];
						break;
					}
				}
				if (val == null)
				{
					return true;
				}
				string hostName = val.m_socket.GetHostName();
				string text = hostName.Replace("Steam_", "");
				if (IsAdminUser(text))
				{
					return true;
				}
				string path = Path.Combine(Utils.GetSaveDataPath((FileSource)2), "ValhallaData", "characters", text);
				if (!Directory.Exists(path))
				{
					Directory.CreateDirectory(path);
				}
			}
			catch
			{
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(Terminal), "TryRunCommand")]
	public static class Patch_Terminal_TryRunCommand
	{
		public static bool Prefix(Terminal __instance, string text)
		{
			Player localPlayer = Player.m_localPlayer;
			if ((Object)(object)localPlayer != (Object)null && IsAdminPlayer(localPlayer))
			{
				return true;
			}
			string text2 = ((text != null) ? text.Trim().ToLower() : "");
			if (text2.StartsWith("devcommands") || text2.StartsWith("god") || text2.StartsWith("fly") || text2.StartsWith("ghost") || text2.StartsWith("spawn") || text2.StartsWith("item") || text2.StartsWith("raiseskill") || text2.StartsWith("tod") || text2.StartsWith("env"))
			{
				MessageHud.instance.ShowMessage((MessageType)2, "<color=red><b>Nincs admin jogosultságod ehhez a parancshoz!</b></color>", 0, (Sprite)null, false, true);
				Debug.LogWarning((object)$"[ValhallaCore Security] Csalási kísérlet blokkolva: {text}");
				return false;
			}
			if (text2 == "/unstuck" || text2 == "unstuck")
			{
				HandleUnstuckCommand(localPlayer);
				return false;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(TombStone), "Interact")]
	public static class Patch_TombStone_Interact
	{
		public static bool Prefix(TombStone __instance, Humanoid character, bool hold, bool alt, ref bool __result)
		{
			if (!TombstoneProtectionEnabled)
			{
				return true;
			}
			if ((Object)(object)__instance == (Object)null || (Object)(object)character == (Object)null)
			{
				return true;
			}
			Player val = (Player)(object)((character is Player) ? character : null);
			if ((Object)(object)val != (Object)null)
			{
				if (IsAdminPlayer(val))
				{
					return true;
				}
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				if ((Object)(object)component != (Object)null && component.IsValid())
				{
					long num = component.GetZDO().GetLong("playerID", 0L);
					long playerID = val.GetPlayerID();
					if (num != 0 && num != playerID)
					{
						((Character)val).Message((MessageType)2, "<color=red><b>Ez a sírkő más harcosé! Nem foszthatod ki!</b></color>", 0, (Sprite)null, false);
						__result = false;
						return false;
					}
				}
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(InventoryGui), "Show")]
	public static class Patch_InventoryGui_Show
	{
		public static void Postfix(InventoryGui __instance, Container container)
		{
			if (AutoRepairEnabled && !((Object)(object)__instance == (Object)null))
			{
				Player localPlayer = Player.m_localPlayer;
				if ((Object)(object)localPlayer != (Object)null && (Object)(object)localPlayer.GetCurrentCraftingStation() != (Object)null && (Object)(object)__instance.m_repairButton != (Object)null && ((Selectable)__instance.m_repairButton).interactable)
				{
					((UnityEvent)__instance.m_repairButton.onClick).Invoke();
				}
			}
		}
	}

	[HarmonyPatch(typeof(ObjectDB), "Awake")]
	public static class Patch_ObjectDB_Awake
	{
		public static void Postfix(ObjectDB __instance)
		{
			if ((Object)(object)__instance == (Object)null || __instance.m_items == null)
			{
				return;
			}
			for (int i = 0; i < __instance.m_items.Count; i++)
			{
				GameObject val = __instance.m_items[i];
				if ((Object)(object)val == (Object)null)
				{
					continue;
				}
				ItemDrop component = val.GetComponent<ItemDrop>();
				if (!((Object)(object)component == (Object)null) && component.m_itemData != null && component.m_itemData.m_shared != null)
				{
					SharedData shared = component.m_itemData.m_shared;
					if (shared.m_maxStackSize > 1)
					{
						shared.m_maxStackSize = Mathf.RoundToInt((float)shared.m_maxStackSize * StackMultiplier);
						shared.m_weight *= WeightMultiplier;
					}
				}
			}
		}
	}

	[HarmonyPatch(typeof(EnvMan), "FixedUpdate")]
	public static class Patch_EnvMan_SleepCheck
	{
		public static void Postfix(EnvMan __instance)
		{
			if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			List<ZNetPeer> peers = ZNet.instance.GetPeers();
			if (peers.Count == 0)
			{
				return;
			}
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < peers.Count; i++)
			{
				ZNetPeer val = peers[i];
				if (val.IsReady())
				{
					num++;
				}
			}
			if (num > 0 && (float)num2 / (float)num >= SleepPercentageRequired)
			{
				__instance.SkipToMorning();
			}
		}
	}

	[HarmonyPatch(typeof(Character), "Awake")]
	public static class Patch_Character_Awake
	{
		public static void Postfix(Character __instance)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || __instance is Player || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
			{
				return;
			}
			string text = ((Object)((Component)__instance).gameObject).name.Replace("(Clone)", "").Trim();
			if (IsBossName(text))
			{
				float maxHealth = __instance.GetMaxHealth();
				int num = GetPlayersNearbyCount(((Component)__instance).transform.position, 100f);
				if (num < 1)
				{
					num = 1;
				}
				float num2 = 1f + (float)(num - 1) * 0.5f;
				float num3 = maxHealth * num2;
				__instance.SetMaxHealth(num3);
				__instance.SetHealth(num3);
				Debug.Log((object)$"[ValhallaCore Raid] Boss {text} életereje beállítva: {num3} HP ({num} harcos, {num2}x szorzó).");
			}
		}
	}

	[HarmonyPatch(typeof(Minimap), "Update")]
	public static class Patch_Minimap_Update
	{
		private static GameObject _countdownTextObj;

		private static Text _countdownText;

		public static void Postfix(Minimap __instance)
		{
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)__instance == (Object)null || (Object)(object)__instance.m_largeRoot == (Object)null)
			{
				return;
			}
			if (__instance.m_largeRoot.activeInHierarchy && (IsRaidCountdown || IsRaidActive))
			{
				if ((Object)(object)_countdownTextObj == (Object)null)
				{
					_countdownTextObj = new GameObject("Valhalla_RaidCountdown");
					_countdownTextObj.transform.SetParent(__instance.m_largeRoot.transform, false);
					RectTransform val = _countdownTextObj.AddComponent<RectTransform>();
					val.anchorMin = new Vector2(1f, 0f);
					val.anchorMax = new Vector2(1f, 0f);
					val.pivot = new Vector2(1f, 0f);
					val.anchoredPosition = new Vector2(-30f, 40f);
					val.sizeDelta = new Vector2(380f, 65f);
					_countdownText = _countdownTextObj.AddComponent<Text>();
					_countdownText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
					_countdownText.fontSize = 15;
					_countdownText.alignment = (TextAnchor)5;
					((Graphic)_countdownText).color = new Color(0.98f, 0.75f, 0.14f);
				}
				if (IsRaidCountdown)
				{
					float num = Mathf.Max(0f, RaidTargetTime - Time.time);
					int num2 = (int)(num / 60f);
					int num3 = (int)(num % 60f);
					_countdownText.text = $"⚔\ufe0f VILÁG BOSS OSTROM KEZDETÉIG: {num2:D2}:{num3:D2}\n\ud83d\udccd Helyszín: {RaidLocationBiome} ({RaidBossName})";
				}
				else if (IsRaidActive)
				{
					_countdownText.text = $"⚔\ufe0f A BOSS MEGJELENT! AZ OSTROM FOLYAMATBAN!\n\ud83d\udccd Helyszín: {RaidLocationBiome} ({RaidBossName})";
				}
			}
			else if ((Object)(object)_countdownTextObj != (Object)null && _countdownTextObj.activeSelf)
			{
				_countdownTextObj.SetActive(false);
			}
		}
	}

	[HarmonyPatch(typeof(Localization), "SetupLanguage")]
	public static class Patch_Localization_SetupLanguage
	{
		public static void Postfix(Localization __instance, string language)
		{
			if (__instance == null)
			{
				return;
			}
			try
			{
				string path = Path.Combine(Paths.ConfigPath, "ValhallaTranslations");
				if (Directory.Exists(path))
				{
					string[] files = Directory.GetFiles(path, "*.json", SearchOption.AllDirectories);
					for (int i = 0; i < files.Length; i++)
					{
						string text = File.ReadAllText(files[i], Encoding.UTF8);
					}
				}
			}
			catch
			{
			}
		}
	}

	public const string ModGUID = "hu.valhalla.server.core";

	public const string ModName = "ValhallaCore Master Engine";

	public const string ModVersion = "1.0.0";

	public static ValhallaCorePlugin Instance;

	public static Harmony HarmonyInstance;

	public static int MaxCharactersPerAccount = 5;

	public static float StackMultiplier = 2f;

	public static float WeightMultiplier = 0.8f;

	public static float SleepPercentageRequired = 0.5f;

	public static bool AutoRepairEnabled = true;

	public static bool TombstoneProtectionEnabled = true;

	public static bool DiscordGatewayEnabled = false;

	public static HashSet<string> AdminSteamIDs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	private static FieldInfo _allAreasField = typeof(PrivateArea).GetField("m_allAreas", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

	public static bool IsRaidActive = false;

	public static bool IsRaidCountdown = false;

	public static float RaidTargetTime = 0f;

	public static string RaidBossName = "Eikthyr";

	public static Vector3 RaidLocation = Vector3.zero;

	public static string RaidLocationBiome = "Rétvidék";

	private float _adminCheckTimer = 0f;

	private float _janitorTimer = 0f;

	private void Awake()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		Instance = this;
		LoadAdminList();
		HarmonyInstance = new Harmony("hu.valhalla.server.core");
		HarmonyInstance.PatchAll();
		ApplyNetworkBufferOptimization();
		((BaseUnityPlugin)this).Logger.LogInfo((object)"[ValhallaCore] v1.0.0 betöltve! 9 alrendszer aktív (Admin Ward, 5 Karakter, Sírkővédelem, Raid Motor, Auto-Repair, Stack 2x).");
	}

	private void Update()
	{
		_adminCheckTimer += Time.deltaTime;
		if (_adminCheckTimer >= 30f)
		{
			_adminCheckTimer = 0f;
			LoadAdminList();
		}
		_janitorTimer += Time.deltaTime;
		if (_janitorTimer >= 600f)
		{
			_janitorTimer = 0f;
			RunGroundJanitor();
		}
	}

	public static void LoadAdminList()
	{
		try
		{
			string path = Path.Combine(Utils.GetSaveDataPath((FileSource)2), "adminlist.txt");
			if (!File.Exists(path))
			{
				return;
			}
			string[] array = File.ReadAllLines(path);
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (!string.IsNullOrEmpty(text) && !text.StartsWith("//"))
				{
					hashSet.Add(text.Replace("Steam_", ""));
					hashSet.Add("Steam_" + text.Replace("Steam_", ""));
				}
			}
			AdminSteamIDs = hashSet;
		}
		catch
		{
		}
	}

	public static bool IsAdminUser(string steamId)
	{
		if (string.IsNullOrEmpty(steamId))
		{
			return false;
		}
		string text = steamId.Replace("Steam_", "");
		return AdminSteamIDs.Contains(text) || AdminSteamIDs.Contains("Steam_" + text);
	}

	public static bool IsAdminPlayer(Player player)
	{
		if ((Object)(object)player == (Object)null)
		{
			return false;
		}
		if ((Object)(object)ZNet.instance == (Object)null)
		{
			return false;
		}
		if (ZNet.instance.IsServer() && !ZNet.instance.IsDedicated())
		{
			return true;
		}
		string playerSteamId = GetPlayerSteamId(player);
		return IsAdminUser(playerSteamId);
	}

	public static string GetPlayerSteamId(Player player)
	{
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0085: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)player == (Object)null)
		{
			return "";
		}
		ZNetView component = ((Component)player).GetComponent<ZNetView>();
		if ((Object)(object)component == (Object)null || component.GetZDO() == null)
		{
			return "";
		}
		if ((Object)(object)ZNet.instance != (Object)null)
		{
			List<ZNetPeer> peers = ZNet.instance.GetPeers();
			for (int i = 0; i < peers.Count; i++)
			{
				ZNetPeer val = peers[i];
				if (val.m_characterID == component.GetZDO().m_uid)
				{
					return val.m_socket.GetHostName();
				}
			}
		}
		return "";
	}

	public static void ApplyNetworkBufferOptimization()
	{
		try
		{
			FieldInfo field = typeof(ZSocket).GetField("m_maxRecvBuffer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (field != null)
			{
				field.SetValue(null, 524288);
			}
		}
		catch
		{
		}
	}

	public static void RunGroundJanitor()
	{
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
		{
			return;
		}
		try
		{
			int num = 0;
			ItemDrop[] array = Object.FindObjectsOfType<ItemDrop>();
			foreach (ItemDrop val in array)
			{
				if ((Object)(object)val == (Object)null || (Object)(object)((Component)val).gameObject == (Object)null)
				{
					continue;
				}
				ZNetView component = ((Component)val).GetComponent<ZNetView>();
				if ((Object)(object)component == (Object)null || !component.IsValid() || val.m_itemData == null || val.m_itemData.m_shared == null)
				{
					continue;
				}
				string name = val.m_itemData.m_shared.m_name;
				switch (name)
				{
				default:
					if (!(name == "$item_dandelion"))
					{
						continue;
					}
					break;
				case "$item_stone":
				case "$item_wood":
				case "$item_resin":
					break;
				}
				if (!IsInsideAdminWard(((Component)val).transform.position))
				{
					component.ClaimOwnership();
					component.Destroy();
					num++;
				}
			}
			if (num > 0)
			{
				Debug.Log((object)$"[ValhallaCore] Ground Janitor: {num} felesleges szemetet takarított el.");
			}
		}
		catch
		{
		}
	}

	public static bool IsInsideAdminWard(Vector3 pos)
	{
		//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
		if (_allAreasField == null)
		{
			return false;
		}
		if (!(_allAreasField.GetValue(null) is List<PrivateArea> list))
		{
			return false;
		}
		for (int i = 0; i < list.Count; i++)
		{
			PrivateArea val = list[i];
			if ((Object)(object)val != (Object)null && (Object)(object)((Component)val).GetComponent<ZNetView>() != (Object)null && ((Component)val).GetComponent<ZNetView>().IsValid() && ((Component)val).GetComponent<ZNetView>().GetZDO().GetBool("Valhalla_AdminWard", false) && Vector3.Distance(((Component)val).transform.position, pos) <= val.m_radius)
			{
				return true;
			}
		}
		return false;
	}

	public static void HandleUnstuckCommand(Player player)
	{
		if (!((Object)(object)player == (Object)null))
		{
			MessageHud.instance.ShowMessage((MessageType)2, "<color=yellow><b>Beragadás feloldása folyamatban (3 mp)...</b></color>", 0, (Sprite)null, false, true);
			((MonoBehaviour)Instance).StartCoroutine(UnstuckCoroutine(player));
		}
	}

	private static IEnumerator UnstuckCoroutine(Player player)
	{
		yield return (object)new WaitForSeconds(3f);
		if ((Object)(object)player != (Object)null)
		{
			Vector3 val = ((Component)player).transform.position + Vector3.up * 2.5f;
			((Character)player).TeleportTo(val, ((Component)player).transform.rotation, true);
			MessageHud.instance.ShowMessage((MessageType)2, "<color=green><b>Sikeres feloldás!</b></color>", 0, (Sprite)null, false, true);
		}
	}

	public static bool IsBossName(string name)
	{
		int result;
		switch (name)
		{
		default:
			result = ((name == "Fader") ? 1 : 0);
			break;
		case "Eikthyr":
		case "gd_king":
		case "Bonemass":
		case "Dragon":
		case "GoblinKing":
		case "SeekerQueen":
			result = 1;
			break;
		}
		return (byte)result != 0;
	}

	public static int GetPlayersNearbyCount(Vector3 pos, float range)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		return Player.GetPlayersInRangeXZ(pos, range);
	}
}