Decompiled source of AMnesia v1.0.4

AMnesia.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("AMnesia")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Azumatt")]
[assembly: AssemblyProduct("AMnesia")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("E0E2F92E-557C-4A05-9D89-AA92A0BD75C4")]
[assembly: AssemblyFileVersion("1.0.4")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.4.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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;
		}
	}
}
namespace AMnesia
{
	[BepInPlugin("Azumatt.AMnesia", "AMnesia", "1.0.4")]
	public class AMnesiaPlugin : BaseUnityPlugin
	{
		public enum Toggle
		{
			On = 1,
			Off = 0
		}

		private class ConfigurationManagerAttributes
		{
			[UsedImplicitly]
			public int? Order;

			[UsedImplicitly]
			public bool? Browsable;

			[UsedImplicitly]
			public string? Category;

			[UsedImplicitly]
			public Action<ConfigEntryBase>? CustomDrawer;
		}

		internal const string ModName = "AMnesia";

		internal const string ModVersion = "1.0.4";

		internal const string Author = "Azumatt";

		private const string ModGUID = "Azumatt.AMnesia";

		private static string ConfigFileName = "Azumatt.AMnesia.cfg";

		private static string ConfigFileFullPath;

		internal static string ConnectionError;

		private readonly Harmony _harmony = new Harmony("Azumatt.AMnesia");

		public static readonly ManualLogSource AMnesiaLogger;

		internal static ConfigEntry<Toggle> turnOffDayMessage;

		public void Awake()
		{
			turnOffDayMessage = config("1 - General", "Turn off Day Message", Toggle.On, "If on, the mod will disable the day count message when attempting to display it on the player's screen.");
			Assembly executingAssembly = Assembly.GetExecutingAssembly();
			_harmony.PatchAll(executingAssembly);
			SetupWatcher();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}

		private void SetupWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName);
			fileSystemWatcher.Changed += ReadConfigValues;
			fileSystemWatcher.Created += ReadConfigValues;
			fileSystemWatcher.Renamed += ReadConfigValues;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void ReadConfigValues(object sender, FileSystemEventArgs e)
		{
			if (!File.Exists(ConfigFileFullPath))
			{
				return;
			}
			try
			{
				AMnesiaLogger.LogDebug((object)"ReadConfigValues called");
				((BaseUnityPlugin)this).Config.Reload();
			}
			catch
			{
				AMnesiaLogger.LogError((object)("There was an issue loading your " + ConfigFileName));
				AMnesiaLogger.LogError((object)"Please check your config entries for spelling and format!");
			}
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description)
		{
			return ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description);
		}

		private ConfigEntry<T> config<T>(string group, string name, T value, string description)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()));
		}

		static AMnesiaPlugin()
		{
			string configPath = Paths.ConfigPath;
			char directorySeparatorChar = Path.DirectorySeparatorChar;
			ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName;
			ConnectionError = "";
			AMnesiaLogger = Logger.CreateLogSource("AMnesia");
			turnOffDayMessage = null;
		}
	}
	[HarmonyPatch(typeof(Player), "Message")]
	internal static class PlayerMessagePatch
	{
		[HarmonyPatch(typeof(MessageHud), "ShowMessage")]
		private static class MessageHudShowMessagePatch
		{
			private static bool Prefix(MessageHud __instance, MessageType type, string text, int amount = 0, Sprite icon = null)
			{
				if (Hud.IsUserHidden())
				{
					return false;
				}
				if (text == Localization.instance.Localize("$msg_newday", new string[1] { EnvMan.instance.GetCurrentDay().ToString() }) && AMnesiaPlugin.turnOffDayMessage.Value == AMnesiaPlugin.Toggle.On)
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(Minimap), "AddPin")]
		private static class MinimapAddPinPatch
		{
			private static void Postfix(Minimap __instance, Vector3 pos, PinType type, string name, bool save, bool isChecked, long ownerID = 0L)
			{
				foreach (PinData pin in __instance.m_pins)
				{
					if (pin.m_name == $"$hud_mapday {EnvMan.instance.GetDay(ZNet.instance.GetTimeSeconds())}")
					{
						pin.m_name = "";
					}
					else if (pin.m_name.Contains("$hud_mapday"))
					{
						pin.m_name = "";
					}
				}
			}
		}

		private static bool Prefix(Player __instance, MessageType type, string msg, int amount = 0, Sprite icon = null)
		{
			if ((Object)(object)((Character)__instance).m_nview == (Object)null || !((Character)__instance).m_nview.IsValid())
			{
				return false;
			}
			if ((Object)(object)Player.m_localPlayer == (Object)null)
			{
				return false;
			}
			if (msg == Localization.instance.Localize("$msg_newday", new string[1] { EnvMan.instance.GetCurrentDay().ToString() }) && AMnesiaPlugin.turnOffDayMessage.Value == AMnesiaPlugin.Toggle.On)
			{
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
	public static class RegisterAndCheckVersion
	{
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			AMnesiaPlugin.AMnesiaLogger.LogDebug((object)"Registering version RPC handler");
			peer.m_rpc.Register<ZPackage>("AMnesia_VersionCheck", (Action<ZRpc, ZPackage>)RpcHandlers.RPC_AMnesia_Version);
			AMnesiaPlugin.AMnesiaLogger.LogInfo((object)"Invoking version check");
			ZPackage val = new ZPackage();
			val.Write("1.0.4");
			peer.m_rpc.Invoke("AMnesia_VersionCheck", new object[1] { val });
		}
	}
	[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
	public static class VerifyClient
	{
		private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance)
		{
			if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc))
			{
				return true;
			}
			AMnesiaPlugin.AMnesiaLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting"));
			rpc.Invoke("Error", new object[1] { 3 });
			return false;
		}

		private static void Postfix(ZNet __instance)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Expected O, but got Unknown
			ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RequestAdminSync", new object[1] { (object)new ZPackage() });
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	public class ShowConnectionError
	{
		private static void Postfix(FejdStartup __instance)
		{
			if (__instance.m_connectionFailedPanel.activeSelf)
			{
				__instance.m_connectionFailedError.fontSizeMax = 25f;
				__instance.m_connectionFailedError.fontSizeMin = 15f;
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + AMnesiaPlugin.ConnectionError;
			}
		}
	}
	[HarmonyPatch(typeof(ZNet), "Disconnect")]
	public static class RemoveDisconnectedPeerFromVerified
	{
		private static void Prefix(ZNetPeer peer, ref ZNet __instance)
		{
			if (__instance.IsServer())
			{
				AMnesiaPlugin.AMnesiaLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list"));
				RpcHandlers.ValidatedPeers.Remove(peer.m_rpc);
			}
		}
	}
	public static class RpcHandlers
	{
		public static readonly List<ZRpc> ValidatedPeers = new List<ZRpc>();

		public static void RPC_AMnesia_Version(ZRpc rpc, ZPackage pkg)
		{
			string text = pkg.ReadString();
			AMnesiaPlugin.AMnesiaLogger.LogInfo((object)("Version check, local: 1.0.4,  remote: " + text));
			if (text != "1.0.4")
			{
				AMnesiaPlugin.ConnectionError = "AMnesia Installed: 1.0.4\n Needed: " + text;
				if (ZNet.instance.IsServer())
				{
					AMnesiaPlugin.AMnesiaLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting"));
					rpc.Invoke("Error", new object[1] { 3 });
				}
			}
			else if (!ZNet.instance.IsServer())
			{
				AMnesiaPlugin.AMnesiaLogger.LogInfo((object)"Received same version from server!");
			}
			else
			{
				AMnesiaPlugin.AMnesiaLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list"));
				ValidatedPeers.Add(rpc);
			}
		}
	}
}