Decompiled source of PassWard v1.0.0

PassWard.dll

Decompiled 3 months ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("PassWard")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PassWard")]
[assembly: AssemblyCopyright("Copyright © 2023")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("f51143e3-8886-4bc6-901c-89f307cc9714")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
namespace PassWard
{
	public class PluginConfig
	{
		public static ConfigEntry<bool> IsModEnabled { get; private set; }

		public static ConfigEntry<KeyboardShortcut> EnterPasswordKey { get; private set; }

		public static ConfigEntry<KeyboardShortcut> RemovePasswordKey { get; private set; }

		public static void BindConfig(ConfigFile config)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			IsModEnabled = config.Bind<bool>("_Global", "isModEnabled", true, "Globally enable or disable this mod.");
			EnterPasswordKey = config.Bind<KeyboardShortcut>("Hotkeys", "enterPasswordShortcut", new KeyboardShortcut((KeyCode)112, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Enter password into a passworded ward OR assign password to own ward.");
			RemovePasswordKey = config.Bind<KeyboardShortcut>("Hotkeys", "removePasswordKey", new KeyboardShortcut((KeyCode)114, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }), "Removes password on player's own passworded ward.");
		}
	}
	public class TryPassword : TextReceiver
	{
		private ZNetView zNetView;

		public TryPassword(ZNetView zNetView)
		{
			this.zNetView = zNetView;
		}

		string TextReceiver.GetText()
		{
			return "";
		}

		void TextReceiver.SetText(string enteredPassword)
		{
			int @int = zNetView.GetZDO().GetInt(PassWard.PasswordZdoFieldHash, -1);
			if (@int == -1)
			{
				PassWard.ShowMessage("No password on ward.");
			}
			else if (StringExtensionMethods.GetStableHashCode(enteredPassword) != @int)
			{
				PassWard.ShowMessage("Incorrect password.");
			}
			else
			{
				OptPlayerIn();
			}
		}

		public string GetText(TextReceiver tr)
		{
			return tr.GetText();
		}

		private void OptPlayerIn()
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Expected O, but got Unknown
			PrivateArea val = default(PrivateArea);
			if (!((Component)zNetView).gameObject.TryGetComponent<PrivateArea>(ref val) || !Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				PassWard.LogError("Error opting-in after password success.");
				return;
			}
			if (val.IsPermitted(Player.m_localPlayer.GetPlayerID()))
			{
				PassWard.ShowMessage("Already opted-in.");
				return;
			}
			val.AddPermitted(Player.m_localPlayer.GetPlayerID(), Player.m_localPlayer.GetPlayerName());
			PassWard.ShowMessage("Password accepted.");
			Talker val2 = default(Talker);
			if (((Component)Player.m_localPlayer).TryGetComponent<Talker>(ref val2))
			{
				UserInfo val3 = new UserInfo();
				val3.Name = val.GetCreatorName() + "'s Ward";
				val3.Gamertag = UserInfo.GetLocalPlayerGamertag();
				val3.NetworkUserId = PrivilegeManager.GetNetworkUserId();
				val2.m_nview.InvokeRPC(ZNetView.Everybody, "Say", new object[4]
				{
					1,
					val3,
					"Password accepted.",
					PrivilegeManager.GetNetworkUserId()
				});
			}
		}
	}
	public class WardPassword : TextReceiver
	{
		private ZNetView zNetView;

		public WardPassword(ZNetView zNetView)
		{
			this.zNetView = zNetView;
		}

		string TextReceiver.GetText()
		{
			return "";
		}

		void TextReceiver.SetText(string password)
		{
			zNetView.GetZDO().Set(PassWard.PasswordZdoFieldHash, StringExtensionMethods.GetStableHashCode(password), false);
			PassWard.ShowMessage("Password set.");
		}

		public string GetText(TextReceiver tr)
		{
			return tr.GetText();
		}
	}
	[BepInPlugin("bruce.valheim.mods.passward", "PassWard", "1.0.0")]
	public sealed class PassWard : BaseUnityPlugin
	{
		public const string PluginGuid = "bruce.valheim.mods.passward";

		public const string PluginName = "PassWard";

		public const string PluginVersion = "1.0.0";

		private Harmony _harmony;

		internal static ManualLogSource _logger;

		public static readonly int WardHash = StringExtensionMethods.GetStableHashCode("guard_stone");

		public static readonly int PasswordZdoFieldHash = StringExtensionMethods.GetStableHashCode("passward.password");

		public static readonly string SetPasswordInputText = "Set password";

		public static readonly string ChangePasswordInputText = "Change password";

		public static readonly string EnterPasswordInputText = "Enter password";

		private void Awake()
		{
			_logger = ((BaseUnityPlugin)this).Logger;
			PluginConfig.BindConfig(((BaseUnityPlugin)this).Config);
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "bruce.valheim.mods.passward");
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}

		public static void ShowMessage(string message)
		{
			if (Object.op_Implicit((Object)(object)MessageHud.instance))
			{
				MessageHud.instance.ShowMessage((MessageType)1, message, 0, (Sprite)null);
			}
		}

		public static void LogError(object o)
		{
			_logger.LogError((object)$"[{DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo)}] {o}");
		}
	}
	[HarmonyPatch(typeof(Hud))]
	public class HudPatch
	{
		private static readonly string _hoverOwnerPasswordTemplate = "{0}\n<size=18>[<color=yellow>{1}</color>] Remove password.</size>\n<size=18>[<color=yellow>{2}</color>] Change password.</size>";

		private static readonly string _hoverOwnerNoneTemplate = "{0}\n<size=18>[<color=yellow>{1}</color>] Add password.</size>";

		private static readonly string _hoverNonownerTemplatePassword = "{0}\n\n<size=18><color=green>Password enabled</color>\n[<color=yellow>{1}</color>] Enter password.</size>";

		private static readonly string _hoverNonownerTemplateNone = "{0}\n\n<size=18><color=red>No password</color>";

		[HarmonyPostfix]
		[HarmonyPatch("UpdateCrosshair")]
		public static void HudUpdateCrosshairPostfix(ref Hud __instance, ref Player player)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
			ZNetView val = default(ZNetView);
			if (PluginConfig.IsModEnabled.Value && Object.op_Implicit((Object)(object)Player.m_localPlayer) && Object.op_Implicit((Object)(object)Player.m_localPlayer.m_hovering) && ((Component)Player.m_localPlayer.m_hovering.transform.root).TryGetComponent<ZNetView>(ref val) && val.IsValid() && StringExtensionMethods.GetStableHashCode(val.GetPrefabName()) == PassWard.WardHash)
			{
				if (IsPlayerOwned(val))
				{
					UpdateOwnerCrosshair(__instance, val);
				}
				else
				{
					UpdateNonownerCrosshair(__instance, val);
				}
				KeyboardShortcut value = PluginConfig.EnterPasswordKey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					EnterPassword(val);
				}
				value = PluginConfig.RemovePasswordKey.Value;
				if (((KeyboardShortcut)(ref value)).IsDown())
				{
					RemovePassword(val);
				}
			}
		}

		private static void UpdateOwnerCrosshair(Hud hud, ZNetView zNetView)
		{
			if (!((Object)(object)hud == (Object)null))
			{
				if (HasPassword(zNetView))
				{
					((TMP_Text)hud.m_hoverName).text = BuildOwnerHoverTextWithPassword(hud);
				}
				else
				{
					((TMP_Text)hud.m_hoverName).text = BuildOwnerHoverTextNoPassword(hud);
				}
			}
		}

		private static string BuildOwnerHoverTextWithPassword(Hud hud)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			return string.Format(_hoverOwnerPasswordTemplate, ((TMP_Text)hud.m_hoverName).text, PluginConfig.RemovePasswordKey.Value, PluginConfig.EnterPasswordKey.Value);
		}

		private static string BuildOwnerHoverTextNoPassword(Hud hud)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return string.Format(_hoverOwnerNoneTemplate, ((TMP_Text)hud.m_hoverName).text, PluginConfig.EnterPasswordKey.Value);
		}

		private static void UpdateNonownerCrosshair(Hud hud, ZNetView zNetView)
		{
			if (!((Object)(object)hud == (Object)null))
			{
				if (!HasPassword(zNetView))
				{
					((TMP_Text)hud.m_hoverName).text = BuildNonownerHoverTextNone(hud);
				}
				else
				{
					((TMP_Text)hud.m_hoverName).text = BuildNonownerHoverTextPassword(hud);
				}
			}
		}

		private static string BuildNonownerHoverTextPassword(Hud hud)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			return string.Format(_hoverNonownerTemplatePassword, ((TMP_Text)hud.m_hoverName).text, PluginConfig.EnterPasswordKey.Value);
		}

		private static string BuildNonownerHoverTextNone(Hud hud)
		{
			return string.Format(_hoverNonownerTemplateNone, ((TMP_Text)hud.m_hoverName).text);
		}

		private static void EnterPassword(ZNetView zNetView)
		{
			if (IsPlayerOwned(zNetView))
			{
				AddPassword(zNetView);
				return;
			}
			int @int = zNetView.GetZDO().GetInt(PassWard.PasswordZdoFieldHash, -1);
			if (@int == -1)
			{
				PassWard.ShowMessage("No password assigned to this ward. Cannot opt in with password.");
				return;
			}
			TryPassword tryPassword = new TryPassword(zNetView);
			TextInput.instance.RequestText((TextReceiver)(object)tryPassword, PassWard.EnterPasswordInputText, 32);
		}

		private static void RemovePassword(ZNetView zNetView)
		{
			if (!IsPlayerOwned(zNetView))
			{
				PassWard.ShowMessage("You do not own this ward. Cannot remove password.");
			}
			else
			{
				zNetView.GetZDO().RemoveInt(PassWard.PasswordZdoFieldHash);
			}
		}

		private static void AddPassword(ZNetView zNetView)
		{
			WardPassword wardPassword = new WardPassword(zNetView);
			if (HasPassword(zNetView))
			{
				TextInput.instance.RequestText((TextReceiver)(object)wardPassword, PassWard.ChangePasswordInputText, 32);
			}
			else
			{
				TextInput.instance.RequestText((TextReceiver)(object)wardPassword, PassWard.SetPasswordInputText, 32);
			}
		}

		private static bool HasPassword(ZNetView zNetView)
		{
			if (zNetView.GetZDO().GetInt(PassWard.PasswordZdoFieldHash, -1) == -1)
			{
				return false;
			}
			return true;
		}

		private static bool IsPlayerOwned(ZNetView zNetView)
		{
			long @long = zNetView.GetZDO().GetLong(ZDOVars.s_creator, 0L);
			if (Player.m_localPlayer.GetPlayerID() != @long)
			{
				return false;
			}
			return true;
		}
	}
}
namespace PassWard.Patches
{
	[HarmonyPatch(typeof(PrivateArea))]
	internal static class PrivateAreaPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("AddUserList")]
		private static bool AddUserList(PrivateArea __instance, StringBuilder text)
		{
			if (!PluginConfig.IsModEnabled.Value)
			{
				return true;
			}
			List<KeyValuePair<long, string>> permittedPlayers = __instance.GetPermittedPlayers();
			text.Append("\n$piece_guardstone_additional: ");
			for (int i = 0; i < permittedPlayers.Count; i++)
			{
				text.Append(permittedPlayers[i].Value);
				if (i != permittedPlayers.Count - 1)
				{
					text.Append("\n");
				}
			}
			return false;
		}
	}
}