Decompiled source of BudylivReconnect v1.0.1

plugins/BudylivReconnect.dll

Decompiled 3 days ago
using System;
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 TMPro;
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: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 BudylivReconnect
{
	[BepInPlugin("com.budyliv.reconnect", "Budyliv Reconnect", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "com.budyliv.reconnect";

		public const string Name = "Budyliv Reconnect";

		public const string Version = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> DelaySeconds;

		internal static ConfigEntry<int> MaxAttempts;

		internal static ConfigEntry<string> Language;

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Expected O, but got Unknown
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Expected O, but got Unknown
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Join the same server again automatically when the connection drops.");
			DelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "DelaySeconds", 3f, new ConfigDescription("Countdown before the first attempt (you can cancel it with Esc or OK). Later attempts wait longer: 5, 10, 15, 20, then 30 s.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>()));
			MaxAttempts = ((BaseUnityPlugin)this).Config.Bind<int>("General", "MaxAttempts", 8, new ConfigDescription("How many times to try before giving up (8 covers about two and a half minutes, enough for a server restart).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 50), Array.Empty<object>()));
			Language = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Language", "Auto", new ConfigDescription("Language of the countdown text. Auto = Ukrainian when the game is in Ukrainian, English otherwise.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Auto", "English", "Ukrainian" }), Array.Empty<object>()));
			_harmony = new Harmony("com.budyliv.reconnect");
			_harmony.PatchAll();
			Log.LogInfo((object)"Budyliv Reconnect 1.0.0 loaded.");
		}

		private void Update()
		{
			try
			{
				Reconnect.Update();
			}
			catch (Exception ex)
			{
				Log.LogError((object)("Update failed: " + ex));
				Reconnect.Stop("error");
			}
		}

		private void OnDestroy()
		{
			Harmony harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
		}
	}
	internal static class Reconnect
	{
		private enum State
		{
			Idle,
			Countdown,
			Joining
		}

		private static readonly float[] RetryDelays = new float[5] { 5f, 10f, 15f, 20f, 30f };

		private static readonly FieldInfo JoinServerField = AccessTools.Field(typeof(FejdStartup), "m_joinServer");

		private static readonly PropertyInfo PasswordProperty = AccessTools.Property(typeof(FejdStartup), "ServerPassword");

		private static State _state = State.Idle;

		private static bool _haveTarget;

		private static ServerJoinData _target;

		private static string _password;

		private static bool _passwordSet;

		private static int _attempt;

		private static bool _wasInWorld;

		private static float _fireAt;

		private static string _panelText;

		private static bool Ukrainian
		{
			get
			{
				string value = Plugin.Language.Value;
				if (!(value == "Ukrainian"))
				{
					if (value == "English")
					{
						return false;
					}
					if (Localization.instance != null)
					{
						return Localization.instance.GetSelectedLanguage() == "Ukrainian";
					}
					return false;
				}
				return true;
			}
		}

		internal static void OnJoinServer(FejdStartup menu)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if (_state == State.Joining)
			{
				return;
			}
			ServerJoinData target = (ServerJoinData)JoinServerField.GetValue(menu);
			if (((ServerJoinData)(ref target)).IsValid)
			{
				if (!_haveTarget || !((ServerJoinData)(ref target)).Equals(_target))
				{
					_password = null;
				}
				_target = target;
				_haveTarget = true;
				_attempt = 0;
			}
		}

		internal static void OnPasswordEntered(string pwd)
		{
			_password = pwd;
		}

		internal unsafe static void OnConnectError(ConnectionStatus statusOverride)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Invalid comparison between Unknown and I4
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Invalid comparison between Unknown and I4
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Invalid comparison between Unknown and I4
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Invalid comparison between Unknown and I4
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Invalid comparison between Unknown and I4
			//IL_013d: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.Enabled.Value || !_haveTarget || _state == State.Countdown)
			{
				return;
			}
			ConnectionStatus val = (((int)statusOverride != 0) ? statusOverride : ZNet.GetConnectionStatus());
			bool num = (int)val == 4 && _wasInWorld;
			bool flag = _state == State.Joining && ((int)val == 5 || (int)val == 4 || (int)val == 7 || (int)val == 9);
			_wasInWorld = false;
			if (!num && !flag)
			{
				if (_state != State.Idle)
				{
					Stop("connection error " + ((object)(*(ConnectionStatus*)(&val))/*cast due to .constrained prefix*/).ToString());
				}
				return;
			}
			if (_attempt >= Plugin.MaxAttempts.Value)
			{
				Stop($"gave up after {_attempt} attempts ({val})");
				return;
			}
			float num2 = ((_attempt == 0) ? Plugin.DelaySeconds.Value : RetryDelays[Mathf.Min(_attempt - 1, RetryDelays.Length - 1)]);
			_state = State.Countdown;
			_fireAt = Time.unscaledTime + num2;
			_panelText = (((Object)(object)FejdStartup.instance != (Object)null && (Object)(object)FejdStartup.instance.m_connectionFailedError != (Object)null) ? FejdStartup.instance.m_connectionFailedError.text : null);
			Plugin.Log.LogInfo((object)$"Connection lost ({val}); reconnecting in {num2:0} s (attempt {_attempt + 1}/{Plugin.MaxAttempts.Value}).");
		}

		internal static void OnConnectionFailedOk()
		{
			if (_state == State.Countdown)
			{
				Stop("cancelled");
			}
		}

		internal static void Update()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Invalid comparison between Unknown and I4
			if ((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer() && (int)ZNet.GetConnectionStatus() == 2)
			{
				_wasInWorld = true;
				if (_state == State.Joining)
				{
					Plugin.Log.LogInfo((object)$"Reconnected (attempt {_attempt}).");
					ClearPassword();
					_state = State.Idle;
				}
				_attempt = 0;
			}
			if (_state != State.Countdown)
			{
				return;
			}
			FejdStartup instance = FejdStartup.instance;
			if ((Object)(object)instance == (Object)null)
			{
				Stop("menu gone");
				return;
			}
			if (Input.GetKeyDown((KeyCode)27))
			{
				Stop("cancelled");
				return;
			}
			float num = _fireAt - Time.unscaledTime;
			if (num > 0f)
			{
				ShowCountdown(instance, Mathf.CeilToInt(num));
			}
			else
			{
				Fire(instance);
			}
		}

		private static void Fire(FejdStartup menu)
		{
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			_attempt++;
			_state = State.Joining;
			RestorePanel(menu);
			if ((Object)(object)menu.m_connectionFailedPanel != (Object)null)
			{
				menu.m_connectionFailedPanel.SetActive(false);
			}
			JoinServerField.SetValue(menu, _target);
			if (!string.IsNullOrEmpty(_password) && PasswordProperty != null)
			{
				PasswordProperty.SetValue(null, _password);
				_passwordSet = true;
			}
			Plugin.Log.LogInfo((object)$"Reconnecting (attempt {_attempt}/{Plugin.MaxAttempts.Value}).");
			menu.JoinServer();
		}

		internal static void Stop(string why)
		{
			if (_state == State.Countdown && (Object)(object)FejdStartup.instance != (Object)null)
			{
				RestorePanel(FejdStartup.instance);
			}
			if (_state != State.Idle)
			{
				Plugin.Log.LogInfo((object)("Auto reconnect stopped: " + why + "."));
			}
			_state = State.Idle;
			_attempt = 0;
			ClearPassword();
		}

		private static void ClearPassword()
		{
			if (_passwordSet && PasswordProperty != null)
			{
				PasswordProperty.SetValue(null, null);
			}
			_passwordSet = false;
		}

		private static void ShowCountdown(FejdStartup menu, int seconds)
		{
			TMP_Text connectionFailedError = menu.m_connectionFailedError;
			if (!((Object)(object)connectionFailedError == (Object)null))
			{
				if ((Object)(object)menu.m_connectionFailedPanel != (Object)null && !menu.m_connectionFailedPanel.activeSelf)
				{
					menu.m_connectionFailedPanel.SetActive(true);
				}
				int num = _attempt + 1;
				int value = Plugin.MaxAttempts.Value;
				string text = (Ukrainian ? $"Перепідключення через {seconds} с (спроба {num} з {value}).\nEsc або OK — скасувати." : $"Reconnecting in {seconds} s (attempt {num} of {value}).\nEsc or OK to cancel.");
				string text2 = (string.IsNullOrEmpty(_panelText) ? text : (_panelText + "\n\n" + text));
				if (connectionFailedError.text != text2)
				{
					connectionFailedError.text = text2;
				}
			}
		}

		private static void RestorePanel(FejdStartup menu)
		{
			if (_panelText != null && (Object)(object)menu.m_connectionFailedError != (Object)null)
			{
				menu.m_connectionFailedError.text = _panelText;
			}
			_panelText = null;
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "JoinServer")]
	internal static class FejdStartup_JoinServer_Patch
	{
		private static void Prefix(FejdStartup __instance)
		{
			Reconnect.OnJoinServer(__instance);
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
	internal static class FejdStartup_ShowConnectError_Patch
	{
		private static void Postfix(ConnectionStatus statusOverride)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Reconnect.OnConnectError(statusOverride);
		}
	}
	[HarmonyPatch(typeof(FejdStartup), "OnConnectionFailedOk")]
	internal static class FejdStartup_OnConnectionFailedOk_Patch
	{
		private static void Prefix()
		{
			Reconnect.OnConnectionFailedOk();
		}
	}
	[HarmonyPatch(typeof(ZNet), "OnPasswordEntered")]
	internal static class ZNet_OnPasswordEntered_Patch
	{
		private static void Prefix(string pwd)
		{
			Reconnect.OnPasswordEntered(pwd);
		}
	}
}