Decompiled source of ForceLguRefund v1.0.1

ForceLguRefund.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.API;
using MoreShipUpgrades.UI.TerminalNodes;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ForceLguRefund")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("ForceLguRefund")]
[assembly: AssemblyTitle("ForceLguRefund")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ForceLguRefund
{
	internal static class HostModGate
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static HandleNamedMessageDelegate <0>__OnMessage;

			public static Action<ulong> <1>__OnClientConnected;
		}

		public const string MessageName = "MrGlim.ForceLguRefund";

		private const byte OpHostHello = 0;

		private const byte OpClientSyncRequest = 1;

		private static bool _registered;

		private static bool _clientConnectedHooked;

		private static bool _requestedSync;

		private static bool _clientHostEnabled;

		public static bool HostHasMod
		{
			get
			{
				EnsureRegistered();
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton == (Object)null)
				{
					return true;
				}
				if (singleton.IsServer || singleton.IsHost)
				{
					return LocalEnabled();
				}
				return _clientHostEnabled;
			}
		}

		public static bool FeaturesActive => HostHasMod;

		private static bool LocalEnabled()
		{
			if (Plugin.Enabled != null)
			{
				return Plugin.Enabled.Value;
			}
			return false;
		}

		public static void Reset()
		{
			_registered = false;
			_clientConnectedHooked = false;
			_requestedSync = false;
			_clientHostEnabled = false;
		}

		public static void EnsureRegistered()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Expected O, but got Unknown
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null)
			{
				_registered = false;
				_clientConnectedHooked = false;
				return;
			}
			if (!_registered)
			{
				CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager;
				object obj = <>O.<0>__OnMessage;
				if (obj == null)
				{
					HandleNamedMessageDelegate val = OnMessage;
					<>O.<0>__OnMessage = val;
					obj = (object)val;
				}
				customMessagingManager.RegisterNamedMessageHandler("MrGlim.ForceLguRefund", (HandleNamedMessageDelegate)obj);
				_registered = true;
				Plugin.Log.LogInfo((object)"MrGlim.ForceLguRefund net handler registered.");
			}
			if (singleton.IsServer && !_clientConnectedHooked)
			{
				singleton.OnClientConnectedCallback += OnClientConnected;
				_clientConnectedHooked = true;
			}
			if (!singleton.IsServer && singleton.IsConnectedClient && !_requestedSync)
			{
				_requestedSync = true;
				RequestSync();
			}
		}

		private static void OnClientConnected(ulong clientId)
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.IsServer && clientId != singleton.LocalClientId)
			{
				SendHello(clientId);
			}
		}

		private static void RequestSync()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && !singleton.IsServer)
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1);
				byte b = 1;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				singleton.CustomMessagingManager.SendNamedMessage("MrGlim.ForceLguRefund", 0uL, val, (NetworkDelivery)2);
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void SendHello(ulong clientId)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager singleton = NetworkManager.Singleton;
			if (!((Object)(object)singleton == (Object)null) && singleton.IsServer)
			{
				FastBufferWriter val = default(FastBufferWriter);
				((FastBufferWriter)(ref val))..ctor(16, (Allocator)2, -1);
				byte b = 0;
				((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref b, default(ForPrimitives));
				bool flag = LocalEnabled();
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				singleton.CustomMessagingManager.SendNamedMessage("MrGlim.ForceLguRefund", clientId, val, (NetworkDelivery)2);
				((FastBufferWriter)(ref val)).Dispose();
			}
		}

		private static void OnMessage(ulong sender, FastBufferReader reader)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			byte b = default(byte);
			((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref b, default(ForPrimitives));
			NetworkManager singleton = NetworkManager.Singleton;
			switch (b)
			{
			case 1:
				if ((Object)(object)singleton != (Object)null && singleton.IsServer)
				{
					SendHello(sender);
				}
				break;
			case 0:
			{
				bool clientHostEnabled = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref clientHostEnabled, default(ForPrimitives));
				if ((Object)(object)singleton != (Object)null && !singleton.IsServer)
				{
					_clientHostEnabled = clientHostEnabled;
					Plugin.Log.LogInfo((object)("Host hello: enabled=" + clientHostEnabled));
				}
				break;
			}
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Disconnect")]
	internal static class HostModGateDisconnectPatch
	{
		public static void Prefix()
		{
			HostModGate.Reset();
			Plugin.Log.LogInfo((object)"MrGlim.ForceLguRefund gate reset on disconnect.");
		}
	}
	[HarmonyPatch]
	internal static class CanRefundUpgradeLevelPatch
	{
		private static MethodBase? TargetMethod()
		{
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UI.Application.UpgradeStoreApplication");
			if (!(type == null))
			{
				return AccessTools.Method(type, "CanRefundUpgradeLevel", (Type[])null, (Type[])null);
			}
			return null;
		}

		[HarmonyPrefix]
		private static bool Prefix(CustomTerminalNode node, ref bool __result)
		{
			if (!HostModGate.FeaturesActive || node == null)
			{
				return true;
			}
			if (node.Unlocked && !node.Refundable)
			{
				node.Refundable = true;
			}
			__result = node.Unlocked;
			return false;
		}
	}
	[HarmonyPatch]
	internal static class ConfirmRefundUpgradeLevelPatch
	{
		private static MethodBase? TargetMethod()
		{
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UI.Application.UpgradeStoreApplication");
			if (!(type == null))
			{
				return AccessTools.Method(type, "ConfirmRefundUpgradeLevel", (Type[])null, (Type[])null);
			}
			return null;
		}

		[HarmonyPrefix]
		private static void Prefix(CustomTerminalNode node)
		{
			if (HostModGate.FeaturesActive && node != null)
			{
				if (!node.Refundable)
				{
					node.Refundable = true;
				}
				Plugin.ForceAllNodesRefundable();
			}
		}
	}
	[BepInPlugin("com.benhough.lethal.ForceLguRefund", "ForceLguRefund", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string ModGuid = "com.benhough.lethal.ForceLguRefund";

		public const string ModName = "ForceLguRefund";

		public const string ModVersion = "1.0.1";

		public const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<int> RefundPercentageOverride;

		internal static ManualLogSource Log { get; private set; }

		private void Awake()
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Force CustomTerminalNode.Refundable=true so the LGU refund UI works as client.");
			RefundPercentageOverride = ((BaseUnityPlugin)this).Config.Bind<int>("General", "RefundPercentageOverride", -1, "If >= 0, override each node's RefundPercentage (0–100 → 0–1). -1 leaves node values (but 0 becomes 1).");
			new Harmony("com.benhough.lethal.ForceLguRefund").PatchAll(typeof(Plugin).Assembly);
			((MonoBehaviour)this).StartCoroutine(ForceRefundableLoop());
			Log.LogInfo((object)"ForceLguRefund v1.0.1 loaded (LGU dep: com.malco.lethalcompany.moreshipupgrades).");
		}

		private IEnumerator ForceRefundableLoop()
		{
			WaitForSeconds wait = new WaitForSeconds(2f);
			while (true)
			{
				try
				{
					ForceAllNodesRefundable();
				}
				catch (Exception ex)
				{
					Log.LogDebug((object)("Force refundable tick skipped: " + ex.Message));
				}
				yield return wait;
			}
		}

		internal static void ForceAllNodesRefundable()
		{
			HostModGate.EnsureRegistered();
			if (!HostModGate.FeaturesActive)
			{
				return;
			}
			List<CustomTerminalNode> upgradeNodes;
			try
			{
				upgradeNodes = UpgradeApi.GetUpgradeNodes();
			}
			catch
			{
				return;
			}
			if (upgradeNodes == null || upgradeNodes.Count == 0)
			{
				return;
			}
			float? num = null;
			int value = RefundPercentageOverride.Value;
			if (value >= 0)
			{
				num = Mathf.Clamp01((float)value / 100f);
			}
			foreach (CustomTerminalNode item in upgradeNodes)
			{
				if (item != null)
				{
					if (!item.Refundable)
					{
						item.Refundable = true;
					}
					if (num.HasValue)
					{
						item.RefundPercentage = num.Value;
					}
					else if (item.RefundPercentage <= 0f)
					{
						item.RefundPercentage = 1f;
					}
				}
			}
			TryForceSyncedRefundConfig();
		}

		private static void TryForceSyncedRefundConfig()
		{
			try
			{
				Type type = AccessTools.TypeByName("MoreShipUpgrades.Managers.UpgradeBus");
				if (type == null)
				{
					return;
				}
				object obj = AccessTools.Property(type, "Instance")?.GetValue(null);
				if (obj == null)
				{
					return;
				}
				object obj2 = AccessTools.Property(type, "PluginConfiguration")?.GetValue(obj);
				if (obj2 == null)
				{
					return;
				}
				object obj3 = AccessTools.Property(obj2.GetType(), "REFUND_UPGRADES")?.GetValue(obj2);
				if (obj3 == null)
				{
					return;
				}
				PropertyInfo propertyInfo = AccessTools.Property(obj3.GetType(), "Value");
				if (!(propertyInfo == null) && propertyInfo.CanWrite)
				{
					object value = propertyInfo.GetValue(obj3);
					if (value is bool && !(bool)value)
					{
						propertyInfo.SetValue(obj3, true);
					}
				}
			}
			catch
			{
			}
		}
	}
	internal static class PluginInfo
	{
		public const string PLUGIN_GUID = "com.benhough.lethal.ForceLguRefund";

		public const string PLUGIN_NAME = "ForceLguRefund";

		public const string PLUGIN_VERSION = "1.0.1";
	}
}