Decompiled source of ServerRepicker v1.2.1

BepInEx/plugins/ServerRepicker/ServerRepicker.dll

Decompiled 3 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using MenuLib;
using MenuLib.MonoBehaviors;
using MenuLib.Structs;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Photon.Voice;
using Photon.Voice.PUN;
using Photon.Voice.Unity;
using Steamworks;
using Steamworks.Data;
using TMPro;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("Photon3Unity3D")]
[assembly: IgnoresAccessChecksTo("PhotonRealtime")]
[assembly: AssemblyCompany("ServerRepicker")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: AssemblyInformationalVersion("1.2.1")]
[assembly: AssemblyProduct("ServerRepicker")]
[assembly: AssemblyTitle("ServerRepicker")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.1.0")]
[module: UnverifiableCode]
[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 ServerRepicker
{
	internal sealed class AvoidList
	{
		private readonly string path;

		private readonly string mutexName;

		private readonly Action<string> warn;

		private readonly object gate = new object();

		private HashSet<string> known = new HashSet<string>(StringComparer.Ordinal);

		private readonly HashSet<string> pending = new HashSet<string>(StringComparer.Ordinal);

		internal AvoidList(string path, Action<string> warn)
		{
			this.path = Path.GetFullPath(path);
			this.warn = warn;
			string s = ((Path.DirectorySeparatorChar == '\\') ? this.path.ToUpperInvariant() : this.path);
			using SHA256 sHA = SHA256.Create();
			mutexName = "ServerRepicker-" + BitConverter.ToString(sHA.ComputeHash(Encoding.UTF8.GetBytes(s)));
		}

		internal bool Contains(string address)
		{
			if (!TryGetIp(address, out var ip))
			{
				return false;
			}
			lock (gate)
			{
				Refresh();
				return pending.Contains(ip) || known.Contains(ip);
			}
		}

		internal bool HasEntries()
		{
			lock (gate)
			{
				Refresh();
				return known.Count > 0 || pending.Count > 0;
			}
		}

		internal string[] Snapshot()
		{
			lock (gate)
			{
				Refresh();
				SortedSet<string> sortedSet = new SortedSet<string>(known, StringComparer.Ordinal);
				sortedSet.UnionWith(pending);
				string[] array = new string[sortedSet.Count];
				sortedSet.CopyTo(array);
				return array;
			}
		}

		private void Refresh()
		{
			try
			{
				known = ReadDisk();
				pending.ExceptWith(known);
			}
			catch (Exception ex) when (IsFileError(ex))
			{
				warn?.Invoke("Could not read the server avoid list: " + ex.Message);
			}
		}

		internal bool Add(string address)
		{
			LocalizedText feedback;
			return Change(address, add: true, rememberOnFailure: true, out feedback);
		}

		internal bool TryAdd(string address, out LocalizedText feedback)
		{
			return Change(address, add: true, rememberOnFailure: false, out feedback);
		}

		internal bool TryRemove(string address, out LocalizedText feedback)
		{
			return Change(address, add: false, rememberOnFailure: false, out feedback);
		}

		private bool Change(string address, bool add, bool rememberOnFailure, out LocalizedText feedback)
		{
			if (!TryGetIp(address, out var ip))
			{
				feedback = new LocalizedText("Enter a valid IPv4 or IPv6 address.", "Введите корректный адрес IPv4 или IPv6.");
				return false;
			}
			lock (gate)
			{
				try
				{
					using Mutex mutex = new Mutex(initiallyOwned: false, mutexName);
					try
					{
						if (!mutex.WaitOne(250))
						{
							throw new IOException("Another process is updating the list.");
						}
					}
					catch (AbandonedMutexException)
					{
					}
					try
					{
						known = ReadDisk();
						SortedSet<string> sortedSet = new SortedSet<string>(known, StringComparer.Ordinal);
						sortedSet.UnionWith(pending);
						bool flag = (add ? sortedSet.Add(ip) : sortedSet.Remove(ip));
						if (!known.SetEquals(sortedSet))
						{
							WriteDisk(sortedSet);
						}
						known = new HashSet<string>(sortedSet, StringComparer.Ordinal);
						pending.Clear();
						if (add)
						{
							feedback = (flag ? new LocalizedText("Added " + ip + ".", "Адрес " + ip + " добавлен.") : new LocalizedText(ip + " is already on the avoid list.", "Адрес " + ip + " уже в списке."));
						}
						else
						{
							feedback = (flag ? new LocalizedText("Removed " + ip + ".", "Адрес " + ip + " удалён.") : new LocalizedText(ip + " is already absent from the avoid list.", "Адреса " + ip + " нет в списке."));
						}
						return flag;
					}
					finally
					{
						mutex.ReleaseMutex();
					}
				}
				catch (Exception ex2) when (IsFileError(ex2) || ex2 is WaitHandleCannotBeOpenedException)
				{
					if (rememberOnFailure)
					{
						feedback = default(LocalizedText);
						warn?.Invoke("Keeping the server IP in memory because the avoid list could not be updated: " + ex2.Message);
						return pending.Add(ip) && !known.Contains(ip);
					}
					feedback = new LocalizedText("Could not save this change. See the BepInEx log.", "Не удалось сохранить изменения. Подробности в журнале BepInEx.");
					warn?.Invoke("Could not save the change to " + ip + ". " + ex2.Message);
					return false;
				}
			}
		}

		private HashSet<string> ReadDisk()
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			try
			{
				using FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
				using StreamReader streamReader = new StreamReader(stream);
				string address;
				while ((address = streamReader.ReadLine()) != null)
				{
					if (TryGetIp(address, out var ip))
					{
						hashSet.Add(ip);
					}
				}
			}
			catch (FileNotFoundException)
			{
			}
			catch (DirectoryNotFoundException)
			{
			}
			return hashSet;
		}

		private void WriteDisk(IEnumerable<string> entries)
		{
			Directory.CreateDirectory(Path.GetDirectoryName(path));
			string sourceFileName = path + ".tmp";
			File.WriteAllLines(sourceFileName, entries);
			if (File.Exists(path))
			{
				File.Replace(sourceFileName, path, null);
			}
			else
			{
				File.Move(sourceFileName, path);
			}
		}

		private static bool IsFileError(Exception e)
		{
			if (!(e is IOException) && !(e is UnauthorizedAccessException))
			{
				return e is SecurityException;
			}
			return true;
		}

		internal static bool TryGetIp(string address, out string ip)
		{
			ip = null;
			if (string.IsNullOrWhiteSpace(address))
			{
				return false;
			}
			string text = address.Trim();
			int num = text.IndexOf("://", StringComparison.Ordinal);
			if (num >= 0)
			{
				if (!Uri.CheckSchemeName(text.Substring(0, num)))
				{
					return false;
				}
				text = text.Substring(num + 3);
				int num2 = text.IndexOfAny(new char[3] { '/', '?', '#' });
				if (num2 >= 0)
				{
					text = text.Substring(0, num2);
				}
			}
			if (text.StartsWith("[", StringComparison.Ordinal))
			{
				int num3 = text.IndexOf(']');
				if (num3 < 0 || (num3 + 1 < text.Length && !IsPort(text.Substring(num3 + 1))))
				{
					return false;
				}
				text = text.Substring(1, num3 - 1);
				if (!text.Contains(":"))
				{
					return false;
				}
			}
			else
			{
				int num4 = text.IndexOf(':');
				if (num4 >= 0 && num4 == text.LastIndexOf(':'))
				{
					if (!IsPort(text.Substring(num4)))
					{
						return false;
					}
					text = text.Substring(0, num4);
				}
			}
			if (!text.Contains(":"))
			{
				string[] array = text.Split('.');
				if (array.Length != 4)
				{
					return false;
				}
				string[] array2 = array;
				foreach (string text2 in array2)
				{
					if (text2.Length == 0 || text2.Length > 3 || (text2.Length > 1 && text2[0] == '0') || !AllDigits(text2))
					{
						return false;
					}
				}
			}
			if (!IPAddress.TryParse(text, out IPAddress address2))
			{
				return false;
			}
			if (address2.AddressFamily == AddressFamily.InterNetworkV6 && address2.IsIPv4MappedToIPv6)
			{
				address2 = address2.MapToIPv4();
			}
			ip = address2.ToString();
			return true;
		}

		private static bool IsPort(string suffix)
		{
			ushort result;
			if (suffix.Length >= 2 && suffix[0] == ':' && AllDigits(suffix.Substring(1)))
			{
				return ushort.TryParse(suffix.Substring(1), out result);
			}
			return false;
		}

		private static bool AllDigits(string text)
		{
			foreach (char c in text)
			{
				if (c < '0' || c > '9')
				{
					return false;
				}
			}
			return true;
		}
	}
	internal sealed class AvoidListMenu : MonoBehaviour
	{
		private sealed class AddressRow
		{
			internal RectTransform Root;

			internal TextMeshProUGUI Label;

			internal REPOButton Action;

			internal string Ip;

			internal bool Listed;
		}

		[CompilerGenerated]
		private static class <>O
		{
			public static BuilderDelegate <0>__AddSettingsEntry;

			public static Action <1>__Open;
		}

		private const int PageSize = 5;

		private const float Width = 252f;

		private static readonly Color Mint = Color32.op_Implicit(new Color32((byte)144, (byte)231, (byte)202, byte.MaxValue));

		private static readonly Color Amber = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)193, (byte)116, byte.MaxValue));

		private static bool registered;

		private REPOPopupPage page;

		private REPOInputField input;

		private TextMeshProUGUI feedback;

		private TextMeshProUGUI count;

		private REPOButton previous;

		private REPOButton next;

		private RectTransform lobbyHeading;

		private RectTransform empty;

		private AddressRow punRow;

		private AddressRow voiceRow;

		private readonly AddressRow[] rows = new AddressRow[5];

		private Action translateLabels;

		private LocalizedText feedbackMessage;

		private int pageNumber;

		private float refreshAt;

		internal static void Register()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			if (!registered)
			{
				object obj = <>O.<0>__AddSettingsEntry;
				if (obj == null)
				{
					BuilderDelegate val = AddSettingsEntry;
					<>O.<0>__AddSettingsEntry = val;
					obj = (object)val;
				}
				MenuAPI.AddElementToSettingsMenu((BuilderDelegate)obj);
				registered = true;
			}
		}

		private static void AddSettingsEntry(Transform parent)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_013e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_015b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_0167: Unknown result type (might be due to invalid IL or missing references)
			//IL_016c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			List<MenuButton> list = new List<MenuButton>();
			Transform obj = parent.Find("Menu Button - Back");
			RectTransform val = (RectTransform)(object)((obj is RectTransform) ? obj : null);
			foreach (Transform item in parent)
			{
				Transform val2 = item;
				MenuButton component = ((Component)val2).GetComponent<MenuButton>();
				if (Object.op_Implicit((Object)(object)component) && (Object)(object)val2 != (Object)(object)val && ((UnityEventBase)component.button.onClick).GetPersistentEventCount() > 0 && ((UnityEventBase)component.button.onClick).GetPersistentTarget(0) is MenuPageSettings)
				{
					list.Add(component);
				}
			}
			Vector2 val3 = default(Vector2);
			((Vector2)(ref val3))..ctor(126f, 66f);
			if ((Object)(object)val != (Object)null && list.Count > 0)
			{
				list.Sort((MenuButton a, MenuButton b) => ((Component)b).transform.localPosition.y.CompareTo(((Component)a).transform.localPosition.y));
				Vector3 localPosition = ((Component)list[0]).transform.localPosition;
				float num = (localPosition.y - ((Transform)val).localPosition.y) / (float)(list.Count + 1);
				for (int num2 = 0; num2 < list.Count; num2++)
				{
					MenuButton obj2 = list[num2];
					Vector3 localPosition2 = ((Component)obj2).transform.localPosition;
					localPosition2.y = localPosition.y - (float)num2 * num;
					Vector3 val4 = (((Component)obj2).transform.localPosition = localPosition2);
					obj2.originalButtonPosition = Vector2.op_Implicit(val4);
				}
				((Vector2)(ref val3))..ctor(localPosition.x, ((Transform)val).localPosition.y + num);
			}
			REPOButton entry = MenuAPI.CreateREPOButton("Server Repicker", (Action)Open, parent, val3);
			entry.menuButton.originalButtonPosition = Vector2.op_Implicit(((Component)entry).transform.localPosition);
			OnLanguageChange(((Component)entry).gameObject, delegate
			{
				((TMP_Text)entry.labelTMP).text = Loc.Pick("Server Repicker", "Выбор сервера");
			});
			MenuPage component2 = ((Component)parent).GetComponent<MenuPage>();
			if (component2 != null)
			{
				component2.WireVerticalNavigation(2f);
			}
		}

		private static void OnLanguageChange(GameObject owner, Action refresh)
		{
			LocalizationChangedEvent obj = owner.AddComponent<LocalizationChangedEvent>();
			obj.localizedAssetRequired = false;
			obj.onLocalizationChanged = new UnityEvent<string>();
			obj.onLocalizationChanged.AddListener((UnityAction<string>)delegate
			{
				refresh();
			});
			refresh();
		}

		private void Translate(TMP_Text label, string russian)
		{
			LocalizedText caption = new LocalizedText(label.text, russian);
			translateLabels = (Action)Delegate.Combine(translateLabels, (Action)delegate
			{
				label.text = caption.Value;
			});
		}

		private static void Open()
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			MenuManager.instance.PageCloseAllAddedOnTop();
			REPOPopupPage val = MenuAPI.CreateREPOPopupPage("Avoided servers", false, true, 2f, (Vector2?)new Vector2(-116f, 0f));
			val.pageDimmerOpacity = 0.91f;
			((Component)val).gameObject.AddComponent<AvoidListMenu>().Build(val);
			val.OpenPage(false);
		}

		private void Build(REPOPopupPage popup)
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			//IL_0280: Unknown result type (might be due to invalid IL or missing references)
			//IL_0295: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0311: Unknown result type (might be due to invalid IL or missing references)
			page = popup;
			page.maskPadding = new Padding(0f, 0f, 0f, 41f);
			Translate((TMP_Text)(object)page.headerTMP, "Исключённые серверы");
			page.AddElementToScrollView((ScrollViewBuilderDelegate)delegate(Transform val)
			{
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Unknown result type (might be due to invalid IL or missing references)
				input = MenuAPI.CreateREPOInputField("Server IP", (Action<string>)Submit, val, default(Vector2), true, "IPv4 or IPv6", "");
				Translate((TMP_Text)(object)input.labelTMP, "IP сервера");
				return ((REPOElement)input).rectTransform;
			}, 0f, 0f);
			RectTransform parent = Band("Add server", 22f);
			MakeButton((Transform)(object)parent, "Add address", delegate
			{
				Submit(input.inputStringSystem.currentValue);
			}, Vector2.zero, 128f, 20f, "Добавить адрес");
			lobbyHeading = Band("Current lobby", 18f);
			Translate((TMP_Text)(object)MakeLabel((Transform)(object)lobbyHeading, "This lobby", 0f, 252f, 18f, 15f, Mint), "Серверы лобби");
			punRow = CreateAddressRow("PUN", live: true);
			voiceRow = CreateAddressRow("Voice", live: true, "Голос");
			RectTransform parent2 = Band("Saved servers", 24f);
			count = MakeLabel((Transform)(object)parent2, "", 0f, 147f, 22f, 17f, Mint);
			previous = MakeButton((Transform)(object)parent2, "Prev", delegate
			{
				TurnPage(-1);
			}, new Vector2(150f, 0f), 48f, 22f, "Назад");
			next = MakeButton((Transform)(object)parent2, "Next", delegate
			{
				TurnPage(1);
			}, new Vector2(202f, 0f), 48f, 22f, "Далее");
			empty = Band("Empty list", 26f);
			Translate((TMP_Text)(object)MakeLabel((Transform)(object)empty, "No servers on your avoid list.", 0f, 252f, 26f, 15f, Color.white), "Список исключений пуст.");
			for (int num = 0; num < rows.Length; num++)
			{
				rows[num] = CreateAddressRow("Saved IP " + (num + 1), live: false);
			}
			RectTransform component = new GameObject("Server list footer", new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
			((Transform)component).SetParent(((Component)page).transform, false);
			component.pivot = Vector2.zero;
			component.sizeDelta = new Vector2(252f, 38f);
			((Transform)component).position = ((Transform)page.maskRectTransform).TransformPoint(new Vector3(5f, -38f, 0f));
			MakeButton((Transform)(object)component, "Back", delegate
			{
				page.ClosePage(false);
			}, Vector2.zero, 58f, 25f, "Закрыть");
			feedback = MakeLabel((Transform)(object)component, "", 61f, 191f, 36f, 13f, Mint);
			((TMP_Text)feedback).textWrappingMode = (TextWrappingModes)1;
			OnLanguageChange(((Component)page).gameObject, delegate
			{
				translateLabels();
				input.inputStringSystem.placeholder = Loc.Pick("IPv4 or IPv6", "IPv4 или IPv6");
				((TMP_Text)feedback).text = feedbackMessage.Value ?? "";
				Refresh();
			});
		}

		private RectTransform Band(string name, float height)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Expected O, but got Unknown
			RectTransform row = new GameObject(name, new Type[1] { typeof(RectTransform) }).GetComponent<RectTransform>();
			((Transform)row).SetParent((Transform)(object)page.menuScrollBox.scroller, false);
			RectTransform obj = row;
			RectTransform obj2 = row;
			Vector2 val = (row.pivot = Vector2.zero);
			Vector2 anchorMin = (obj2.anchorMax = val);
			obj.anchorMin = anchorMin;
			row.sizeDelta = new Vector2(252f, height);
			((Transform)row).localPosition = Vector3.zero;
			page.AddElementToScrollView((ScrollViewBuilderDelegate)((Transform _) => row), 0f, 0f);
			return row;
		}

		private REPOButton MakeButton(Transform parent, string text, Action click, Vector2 position, float width, float height, string russian = null)
		{
			//IL_0003: 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_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: 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)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			REPOButton val = MenuAPI.CreateREPOButton(text, click, parent, position);
			val.menuButton.resizeButton = false;
			val.menuButton.colorNormal = Color32.op_Implicit(new Color32((byte)205, (byte)213, (byte)215, byte.MaxValue));
			RectTransform rectTransform = ((REPOElement)val).rectTransform;
			Vector2 val2 = default(Vector2);
			((Vector2)(ref val2))..ctor(width, height);
			rectTransform.sizeDelta = val2;
			val.overrideButtonSize = val2;
			TextMeshProUGUI labelTMP = val.labelTMP;
			((TMP_Text)labelTMP).enableAutoSizing = true;
			((TMP_Text)labelTMP).fontSizeMin = 11f;
			float fontSize = (((TMP_Text)labelTMP).fontSizeMax = Mathf.Min(18f, height));
			((TMP_Text)labelTMP).fontSize = fontSize;
			((TMP_Text)labelTMP).textWrappingMode = (TextWrappingModes)0;
			((TMP_Text)labelTMP).alignment = (TextAlignmentOptions)4097;
			((TMP_Text)labelTMP).margin = Vector4.zero;
			((TMP_Text)labelTMP).rectTransform.anchorMin = Vector2.zero;
			((TMP_Text)labelTMP).rectTransform.anchorMax = Vector2.one;
			val2 = (((TMP_Text)labelTMP).rectTransform.offsetMin = (((TMP_Text)labelTMP).rectTransform.offsetMax = Vector2.zero));
			if (russian != null)
			{
				Translate((TMP_Text)(object)labelTMP, russian);
			}
			return val;
		}

		private static TextMeshProUGUI MakeLabel(Transform parent, string text, float x, float width, float height, float size, Color color)
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			REPOLabel obj = MenuAPI.CreateREPOLabel(text, parent, new Vector2(x, 0f));
			TextMeshProUGUI labelTMP = obj.labelTMP;
			RectTransform rectTransform = ((REPOElement)obj).rectTransform;
			RectTransform rectTransform2 = ((TMP_Text)labelTMP).rectTransform;
			Vector2 sizeDelta = default(Vector2);
			((Vector2)(ref sizeDelta))..ctor(width, height);
			rectTransform2.sizeDelta = sizeDelta;
			rectTransform.sizeDelta = sizeDelta;
			((TMP_Text)labelTMP).richText = false;
			((Graphic)labelTMP).raycastTarget = false;
			((TMP_Text)labelTMP).enableAutoSizing = true;
			((TMP_Text)labelTMP).fontSizeMin = 10f;
			float fontSize = (((TMP_Text)labelTMP).fontSizeMax = size);
			((TMP_Text)labelTMP).fontSize = fontSize;
			((TMP_Text)labelTMP).alignment = (TextAlignmentOptions)4097;
			((Graphic)labelTMP).color = color;
			return labelTMP;
		}

		private AddressRow CreateAddressRow(string name, bool live, string russian = null)
		{
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			AddressRow row = new AddressRow
			{
				Root = Band(name, 24f)
			};
			float num = (live ? 36f : 0f);
			if (live)
			{
				TextMeshProUGUI label = MakeLabel((Transform)(object)row.Root, name, 0f, num, 24f, 13f, Mint);
				if (russian != null)
				{
					Translate((TMP_Text)(object)label, russian);
				}
			}
			row.Label = MakeLabel((Transform)(object)row.Root, "", num, 185f - num, 24f, 16f, Color.white);
			((TMP_Text)row.Label).textWrappingMode = (TextWrappingModes)1;
			row.Action = MakeButton((Transform)(object)row.Root, live ? "Avoid" : "Remove", delegate
			{
				if (!string.IsNullOrEmpty(row.Ip))
				{
					if (live)
					{
						LossMonitor.GetHostedEndpoints(out var pun, out var voice);
						if (row.Ip != ((row == punRow) ? pun : voice))
						{
							Report(changed: false, new LocalizedText("The lobby connection changed. Check the current IP.", "Подключение изменилось. Проверьте текущий IP."));
							Refresh();
							return;
						}
					}
					if (row.Listed)
					{
						Remove(row.Ip);
					}
					else
					{
						Submit(row.Ip, clearInput: false);
					}
				}
			}, new Vector2(190f, 0f), 61f, 24f);
			return row;
		}

		private static void Show(RectTransform band, bool visible)
		{
			((Component)band).GetComponent<REPOScrollViewElement>().visibility = visible;
		}

		private void SetRow(AddressRow row, string ip, bool visible, bool listed)
		{
			Show(row.Root, visible);
			row.Ip = ip;
			row.Listed = listed;
			if (visible)
			{
				((TMP_Text)row.Label).text = ip ?? Loc.Pick("Unavailable", "Недоступен");
				((Component)row.Action).gameObject.SetActive(ip != null);
				((TMP_Text)row.Action.labelTMP).text = (listed ? Loc.Pick("Remove", "Убрать") : Loc.Pick("Avoid", "Исключить"));
			}
		}

		private void Submit(string address)
		{
			Submit(address, clearInput: true);
		}

		private void Submit(string address, bool clearInput)
		{
			LocalizedText message;
			bool flag = Plugin.Avoided.TryAdd(address, out message);
			if (flag && clearInput)
			{
				input.inputStringSystem.SetValue("", false);
			}
			Report(flag, message);
			Refresh((flag && AvoidList.TryGetIp(address, out var ip)) ? ip : null);
		}

		private void Remove(string address)
		{
			LocalizedText message;
			bool changed = Plugin.Avoided.TryRemove(address, out message);
			Report(changed, message);
			Refresh();
		}

		private void Report(bool changed, LocalizedText message)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			feedbackMessage = message;
			((Graphic)feedback).color = (changed ? Mint : Amber);
			((TMP_Text)feedback).text = message.Value;
		}

		private void TurnPage(int direction)
		{
			pageNumber += direction;
			Refresh();
		}

		private void Refresh(string reveal = null)
		{
			string[] array = Plugin.Avoided.Snapshot();
			if (reveal != null)
			{
				int num = Array.IndexOf(array, reveal);
				if (num >= 0)
				{
					pageNumber = num / 5;
				}
			}
			int num2 = Math.Max(0, (array.Length - 1) / 5);
			pageNumber = Mathf.Clamp(pageNumber, 0, num2);
			int num3 = pageNumber * 5;
			((TMP_Text)count).text = ((num2 == 0) ? string.Format(Loc.Pick("Saved ({0})", "В списке ({0})"), array.Length) : string.Format(Loc.Pick("Saved {0}–{1} of {2}", "В списке {0}–{1} из {2}"), num3 + 1, Math.Min(num3 + 5, array.Length), array.Length));
			((Component)previous).gameObject.SetActive(pageNumber > 0);
			((Component)next).gameObject.SetActive(pageNumber < num2);
			Show(empty, array.Length == 0);
			for (int i = 0; i < rows.Length; i++)
			{
				string text = ((num3 + i < array.Length) ? array[num3 + i] : null);
				SetRow(rows[i], text, text != null, listed: true);
			}
			LossMonitor.GetHostedEndpoints(out var pun, out var voice);
			bool isHosting = LossMonitor.IsHosting;
			Show(lobbyHeading, isHosting);
			SetRow(punRow, pun, isHosting, pun != null && Array.IndexOf(array, pun) >= 0);
			SetRow(voiceRow, voice, isHosting, voice != null && Array.IndexOf(array, voice) >= 0);
			page.scrollView.UpdateElements();
			refreshAt = Time.unscaledTime + 3f;
		}

		private void Update()
		{
			if ((Object)(object)page != (Object)null && page.menuPage.isInteractable && Time.unscaledTime >= refreshAt)
			{
				Refresh();
			}
		}
	}
	internal static class Loc
	{
		internal static bool Russian
		{
			get
			{
				if (LocalizationManager.instance == null)
				{
					return false;
				}
				string text = SemiFunc.LocaleGetCode();
				if (!string.Equals(text, "ru", StringComparison.OrdinalIgnoreCase))
				{
					return text?.StartsWith("ru-", StringComparison.OrdinalIgnoreCase) ?? false;
				}
				return true;
			}
		}

		internal static string Pick(string english, string russian)
		{
			if (!Russian)
			{
				return english;
			}
			return russian;
		}
	}
	internal readonly struct LocalizedText
	{
		private readonly string russian;

		internal string English { get; }

		internal string Value => Loc.Pick(English, russian);

		internal LocalizedText(string english, string russian)
		{
			English = english;
			this.russian = russian;
		}
	}
	internal static class LossMonitor
	{
		private sealed class Activity
		{
			private readonly double joinedAt;

			private double lastEvent = double.NegativeInfinity;

			private double sample = double.NegativeInfinity;

			private double previousSample = double.NegativeInfinity;

			private double oldestSample = double.NegativeInfinity;

			internal Activity(double now)
			{
				joinedAt = now;
			}

			internal void Observe(double now)
			{
				lastEvent = now;
				if (!(now - sample < 0.2))
				{
					oldestSample = previousSample;
					previousSample = sample;
					sample = now;
				}
			}

			internal bool SilentJoin(double now)
			{
				if (double.IsNegativeInfinity(lastEvent) && now - joinedAt >= 5.0)
				{
					return now - joinedAt < 15.0;
				}
				return false;
			}

			internal bool LostActiveStream(double now)
			{
				if (now - lastEvent >= 5.0 && now - lastEvent < 15.0)
				{
					return lastEvent - oldestSample <= 2.5;
				}
				return false;
			}
		}

		[HarmonyPatch(typeof(NetworkConnect), "OnJoinedRoom")]
		internal static class ObserveHostedRoom
		{
			[HarmonyPrefix]
			private static void Prefix()
			{
				if (!IsHosting)
				{
					Reset();
					Player localPlayer = PhotonNetwork.LocalPlayer;
					if (localPlayer != null && localPlayer.ActorNumber == 1 && !localPlayer.HasRejoined && !PhotonNetwork.OfflineMode && PhotonNetwork.InRoom && PhotonNetwork.IsMasterClient)
					{
						hostedRoom = PhotonNetwork.CurrentRoom;
						punServerIp = ServerEndpoint.Current(PhotonNetwork.NetworkingClient);
						voiceRoomName = hostedRoom.Name + "_voice_";
						HasHadGuests = hostedRoom.PlayerCount > 1;
						HostedSince = (lastFrame = Time.realtimeSinceStartupAsDouble);
					}
				}
			}
		}

		[HarmonyPatch(typeof(LoadBalancingClient), "OnEvent")]
		internal static class ObserveRoomEvent
		{
			[HarmonyPostfix]
			private static void Postfix(LoadBalancingClient __instance, EventData __0, bool __runOriginal)
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Invalid comparison between Unknown and I4
				if (!IsHosting || __0 == null || (int)__instance.Server != 1)
				{
					return;
				}
				bool flag = __instance == PhotonNetwork.NetworkingClient;
				if (!flag && !IsHostedVoice(__instance))
				{
					return;
				}
				if (!flag && voiceRoom != __instance.CurrentRoom)
				{
					ClearVoiceRoom(__instance.CurrentRoom);
				}
				int sender = __0.Sender;
				if (sender <= 0 || sender == __instance.LocalPlayer.ActorNumber)
				{
					return;
				}
				if (flag && (__0.Code == byte.MaxValue || __0.Code == 254))
				{
					HasHadGuests = true;
				}
				if (!__runOriginal)
				{
					return;
				}
				Dictionary<int, Activity> dictionary = (flag ? punActors : voiceActors);
				double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
				switch (__0.Code)
				{
				case byte.MaxValue:
					dictionary[sender] = new Activity(realtimeSinceStartupAsDouble);
					if (!flag)
					{
						CheckVoiceReturn(__instance, sender, realtimeSinceStartupAsDouble);
					}
					break;
				case 254:
				{
					dictionary.TryGetValue(sender, out var value2);
					dictionary.Remove(sender);
					bool flag2 = realtimeSinceStartupAsDouble >= observationsResumeAt && realtimeSinceStartupAsDouble - lastFrame <= 2.0;
					if (flag)
					{
						NotePunDeparture(realtimeSinceStartupAsDouble);
						if (flag2 && value2 != null && (value2.SilentJoin(realtimeSinceStartupAsDouble) || value2.LostActiveStream(realtimeSinceStartupAsDouble)))
						{
							Record(punServerIp ?? ServerEndpoint.Current(__instance), "PUN", "probable remote connection loss");
						}
						break;
					}
					object obj = __0[(byte)233];
					if (obj is bool && (bool)obj)
					{
						if (flag2 && value2 != null && value2.SilentJoin(realtimeSinceStartupAsDouble))
						{
							QueueVoiceDecision(__instance, realtimeSinceStartupAsDouble);
						}
						int punActor = GetPunActor(__instance, sender);
						if (punActor > 0)
						{
							voiceInactiveAt[punActor] = realtimeSinceStartupAsDouble;
						}
					}
					break;
				}
				default:
				{
					if (dictionary.TryGetValue(sender, out var value))
					{
						value.Observe(realtimeSinceStartupAsDouble);
					}
					if (!flag && __0.Code == 253)
					{
						CheckVoiceReturn(__instance, sender, realtimeSinceStartupAsDouble);
					}
					break;
				}
				}
			}
		}

		[HarmonyPatch(typeof(LoadBalancingClient), "OpRaiseEvent")]
		internal static class ObserveHostRemoval
		{
			[HarmonyPostfix]
			private static void Postfix(LoadBalancingClient __instance, byte eventCode, object customEventContent, RaiseEventOptions raiseEventOptions, bool __result)
			{
				if (!__result || !IsHosting || __instance != PhotonNetwork.NetworkingClient)
				{
					return;
				}
				if ((eventCode == 123 || eventCode == 124) && customEventContent is object[] array && array.Length != 0 && array[0] is int key)
				{
					punActors.Remove(key);
				}
				else
				{
					if (eventCode != 203 || raiseEventOptions?.TargetActors == null)
					{
						return;
					}
					int[] targetActors = raiseEventOptions.TargetActors;
					foreach (int key2 in targetActors)
					{
						punActors.Remove(key2);
					}
				}
				NotePunDeparture(Time.realtimeSinceStartupAsDouble);
			}
		}

		[HarmonyPatch(typeof(LoadBalancingClient), "OnStatusChanged")]
		internal static class ObserveHostTimeout
		{
			[HarmonyPrefix]
			private static void Prefix(LoadBalancingClient __instance, StatusCode __0)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Invalid comparison between Unknown and I4
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Invalid comparison between Unknown and I4
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Invalid comparison between Unknown and I4
				if (((int)__0 == 1040 || (int)__0 == 1041) && IsHosting && (int)__instance.Server == 1)
				{
					if (__instance == PhotonNetwork.NetworkingClient)
					{
						Record(punServerIp ?? ServerEndpoint.Current(__instance), "PUN", "local transport timeout");
					}
					else if (IsHostedVoice(__instance))
					{
						Record(((voiceRoom == __instance.CurrentRoom) ? voiceServerIp : null) ?? ServerEndpoint.Current(__instance), "Voice", "local transport timeout");
					}
				}
			}
		}

		private const double MinSilentJoin = 5.0;

		private const double MaxSilentJoin = 15.0;

		private const double DepartureGrace = 10.0;

		private const double VoiceReturnWindow = 45.0;

		private static readonly Dictionary<int, Activity> punActors = new Dictionary<int, Activity>();

		private static readonly Dictionary<int, Activity> voiceActors = new Dictionary<int, Activity>();

		private static readonly Dictionary<int, double> voiceInactiveAt = new Dictionary<int, double>();

		private static Room hostedRoom;

		private static Room voiceRoom;

		private static string voiceRoomName;

		private static string punServerIp;

		private static string voiceServerIp;

		private static double lastPunDeparture;

		private static double voiceDecisionAt;

		private static string pendingVoiceAddress;

		private static double lastFrame;

		private static double observationsResumeAt;

		internal static bool IsHosting
		{
			get
			{
				if (hostedRoom != null && !PhotonNetwork.OfflineMode && PhotonNetwork.InRoom && PhotonNetwork.CurrentRoom == hostedRoom)
				{
					return PhotonNetwork.IsMasterClient;
				}
				return false;
			}
		}

		internal static bool HasHadGuests { get; private set; }

		internal static double HostedSince { get; private set; }

		internal static void GetHostedEndpoints(out string pun, out string voice)
		{
			pun = (voice = null);
			if (IsHosting)
			{
				pun = punServerIp ?? ServerEndpoint.Current(PhotonNetwork.NetworkingClient);
				PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
				LoadBalancingTransport val = ((existingInstance != null) ? ((VoiceConnection)existingInstance).Client : null);
				if (val != null && IsHostedVoice((LoadBalancingClient)(object)val))
				{
					voice = ((((LoadBalancingClient)val).CurrentRoom == voiceRoom && voiceServerIp != null) ? voiceServerIp : ServerEndpoint.Current((LoadBalancingClient)(object)val));
				}
			}
		}

		internal static void Reset()
		{
			hostedRoom = null;
			punServerIp = null;
			HasHadGuests = false;
			HostedSince = 0.0;
			voiceRoomName = null;
			punActors.Clear();
			ClearVoiceRoom(null);
			lastPunDeparture = double.NegativeInfinity;
			observationsResumeAt = 0.0;
		}

		private static void ClearVoiceRoom(Room room)
		{
			voiceRoom = room;
			object obj;
			if (room != null)
			{
				PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
				obj = ServerEndpoint.Current((LoadBalancingClient)(object)((existingInstance != null) ? ((VoiceConnection)existingInstance).Client : null));
			}
			else
			{
				obj = null;
			}
			voiceServerIp = (string)obj;
			voiceActors.Clear();
			voiceInactiveAt.Clear();
			pendingVoiceAddress = null;
		}

		private static bool IsHostedVoice(LoadBalancingClient client)
		{
			PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
			if ((object)client == ((existingInstance != null) ? ((VoiceConnection)existingInstance).Client : null) && client.InRoom)
			{
				return client.CurrentRoom.Name == voiceRoomName;
			}
			return false;
		}

		internal static void Tick()
		{
			if (hostedRoom == null)
			{
				return;
			}
			if (!IsHosting)
			{
				Reset();
				return;
			}
			if (hostedRoom.PlayerCount > 1)
			{
				HasHadGuests = true;
			}
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			if (realtimeSinceStartupAsDouble - lastFrame > 2.0)
			{
				observationsResumeAt = realtimeSinceStartupAsDouble + 15.0;
				pendingVoiceAddress = null;
			}
			lastFrame = realtimeSinceStartupAsDouble;
			if (voiceRoom != null)
			{
				PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
				LoadBalancingTransport val = ((existingInstance != null) ? ((VoiceConnection)existingInstance).Client : null);
				if (val == null || !((LoadBalancingClient)val).InRoom || voiceRoom != ((LoadBalancingClient)val).CurrentRoom)
				{
					ClearVoiceRoom(null);
				}
				else if (pendingVoiceAddress != null && realtimeSinceStartupAsDouble >= voiceDecisionAt)
				{
					Record(pendingVoiceAddress, "Voice", "probable remote connection loss");
					pendingVoiceAddress = null;
				}
			}
		}

		private static int GetPunActor(LoadBalancingClient voice, int voiceActor)
		{
			Player player = voice.CurrentRoom.GetPlayer(voiceActor, false);
			if (((player != null) ? player.CustomProperties : null) == null || !(player.CustomProperties[(object)"punActorNumber"] is int num) || num <= 0 || num == PhotonNetwork.LocalPlayer.ActorNumber)
			{
				return 0;
			}
			Player player2 = hostedRoom.GetPlayer(num, false);
			if (player2 == null || player2.IsInactive)
			{
				return 0;
			}
			return num;
		}

		private static void CheckVoiceReturn(LoadBalancingClient voice, int sender, double now)
		{
			if (voiceInactiveAt.Count == 0)
			{
				return;
			}
			Player player = voice.CurrentRoom.GetPlayer(sender, false);
			if (player == null || player.IsInactive)
			{
				return;
			}
			int punActor = GetPunActor(voice, sender);
			if (voiceInactiveAt.TryGetValue(punActor, out var value))
			{
				voiceInactiveAt.Remove(punActor);
				if (now - value <= 45.0)
				{
					QueueVoiceDecision(voice, now);
				}
			}
		}

		private static void QueueVoiceDecision(LoadBalancingClient voice, double now)
		{
			if (!(now - lastPunDeparture < 10.0) && pendingVoiceAddress == null)
			{
				pendingVoiceAddress = voiceServerIp ?? ServerEndpoint.Current(voice);
				voiceDecisionAt = now + 10.0;
			}
		}

		private static void NotePunDeparture(double now)
		{
			lastPunDeparture = now;
			pendingVoiceAddress = null;
			voiceInactiveAt.Clear();
		}

		private static void Record(string address, string service, string reason)
		{
			if (Plugin.Avoided.Add(address))
			{
				Plugin.Log.LogWarning((object)(service + " " + reason + ". Added game server " + address + " to the avoid list."));
			}
		}
	}
	[BepInPlugin("redos.serverrepicker", "ServerRepicker", "1.2.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private const string Guid = "redos.serverrepicker";

		private Harmony patches;

		internal static AvoidList Avoided { get; private set; }

		internal static ManualLogSource Log { get; private set; }

		private void Start()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Avoided = new AvoidList(Path.Combine(Paths.ConfigPath, "ServerRepicker", "avoid-ips.txt"), delegate(string message)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)message);
			});
			patches = new Harmony("redos.serverrepicker");
			try
			{
				patches.PatchAll(typeof(Plugin).Assembly);
				((BaseUnityPlugin)this).Logger.LogInfo((object)"ServerRepicker is ready.");
			}
			catch (Exception ex)
			{
				patches.UnpatchSelf();
				((BaseUnityPlugin)this).Logger.LogError((object)("Could not install the server selection hooks: " + ex));
				((Behaviour)this).enabled = false;
				return;
			}
			if (Chainloader.PluginInfos.ContainsKey("nickklmao.menulib"))
			{
				try
				{
					RegisterMenu();
				}
				catch (Exception ex2)
				{
					((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not register the server list menu: " + ex2));
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void RegisterMenu()
		{
			AvoidListMenu.Register();
		}

		private void Update()
		{
			ServerOffer.Tick();
			LossMonitor.Tick();
			ServerSelection.Tick();
		}

		private void OnDestroy()
		{
			Harmony obj = patches;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			LossMonitor.Reset();
		}
	}
	internal static class ServerEndpoint
	{
		internal static string Current(LoadBalancingClient client)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Invalid comparison between Unknown and I4
			if (client == null || (int)client.Server != 1)
			{
				return null;
			}
			PeerBase val = ((PhotonPeer)(client.LoadBalancingPeer?)).peerBase;
			if (val == null)
			{
				return null;
			}
			if (AvoidList.TryGetIp(val.ServerAddress, out var ip))
			{
				return ip;
			}
			IPhotonSocket photonSocket = val.PhotonSocket;
			SocketUdp val2 = (SocketUdp)(object)((photonSocket is SocketUdp) ? photonSocket : null);
			Socket socket;
			if (val2 == null)
			{
				SocketUdpAsync val3 = (SocketUdpAsync)(object)((photonSocket is SocketUdpAsync) ? photonSocket : null);
				if (val3 == null)
				{
					SocketUdpBlocking val4 = (SocketUdpBlocking)(object)((photonSocket is SocketUdpBlocking) ? photonSocket : null);
					if (val4 == null)
					{
						SocketTcp val5 = (SocketTcp)(object)((photonSocket is SocketTcp) ? photonSocket : null);
						socket = ((val5 != null) ? val5.sock : ((SocketTcpAsync)(((photonSocket is SocketTcpAsync) ? photonSocket : null)?)).sock);
					}
					else
					{
						socket = val4.sock;
					}
				}
				else
				{
					socket = val3.sock;
				}
			}
			else
			{
				socket = val2.sock;
			}
			Socket socket2 = socket;
			try
			{
				if (!(socket2?.RemoteEndPoint is IPEndPoint iPEndPoint))
				{
					return null;
				}
				IPAddress address = iPEndPoint.Address;
				return address.IsIPv4MappedToIPv6 ? address.MapToIPv4().ToString() : address.ToString();
			}
			catch (ObjectDisposedException)
			{
				return null;
			}
			catch (SocketException)
			{
				return null;
			}
		}
	}
	internal static class ServerOffer
	{
		private sealed class Lookup
		{
			internal LoadBalancingClient Client;

			internal EnterRoomParams Request;

			internal OperationResponse Response;

			internal Uri Endpoint;

			internal Task<IPAddress[]> Addresses;

			internal double Deadline;

			internal bool Avoid;
		}

		private static readonly List<Lookup> pending = new List<Lookup>();

		private static Lookup delivering;

		internal static bool? IsAvoided(LoadBalancingClient client, EnterRoomParams request, OperationResponse response, string address)
		{
			if (delivering?.Response == response)
			{
				return delivering.Avoid;
			}
			if (AvoidList.TryGetIp(address, out var ip))
			{
				return Plugin.Avoided.Contains(ip);
			}
			if (!Uri.TryCreate(address.Contains("://") ? address : ("net.tcp://" + address), UriKind.Absolute, out Uri result) || result.HostNameType != UriHostNameType.Dns || !Plugin.Avoided.HasEntries())
			{
				return false;
			}
			Lookup item = new Lookup
			{
				Client = client,
				Request = request,
				Response = response,
				Endpoint = result,
				Addresses = Resolve(result.DnsSafeHost),
				Deadline = Time.realtimeSinceStartupAsDouble + 5.0
			};
			pending.Add(item);
			return null;
		}

		private static async Task<IPAddress[]> Resolve(string host)
		{
			try
			{
				return await Dns.GetHostAddressesAsync(host).ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (SocketException)
			{
				return Array.Empty<IPAddress>();
			}
			catch (ArgumentException)
			{
				return Array.Empty<IPAddress>();
			}
		}

		internal static void Tick()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Invalid comparison between Unknown and I4
			for (int num = pending.Count - 1; num >= 0; num--)
			{
				Lookup lookup = pending[num];
				LoadBalancingClient client = lookup.Client;
				if ((int)client.Server != 0 || (int)client.State != 8 || client.enterRoomParamsCache != lookup.Request)
				{
					pending.RemoveAt(num);
				}
				else if (lookup.Addresses.IsCompleted || !(Time.realtimeSinceStartupAsDouble < lookup.Deadline))
				{
					pending.RemoveAt(num);
					if (lookup.Addresses.Status == TaskStatus.RanToCompletion)
					{
						CheckResolvedAddresses(lookup, lookup.Addresses.Result);
					}
					delivering = lookup;
					try
					{
						client.OnOperationResponse(lookup.Response);
					}
					finally
					{
						delivering = null;
					}
				}
			}
		}

		private static void CheckResolvedAddresses(Lookup item, IPAddress[] addresses)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Invalid comparison between Unknown and I4
			IPAddress iPAddress = null;
			bool flag = false;
			foreach (IPAddress iPAddress2 in addresses)
			{
				if (Plugin.Avoided.Contains(iPAddress2.ToString()))
				{
					flag = true;
				}
				else if (iPAddress == null)
				{
					iPAddress = iPAddress2;
				}
			}
			if (flag)
			{
				ConnectionProtocol usedProtocol = ((PhotonPeer)item.Client.LoadBalancingPeer).UsedProtocol;
				if (iPAddress != null && ((int)usedProtocol == 0 || (int)usedProtocol == 1) && item.Endpoint.Scheme == "net.tcp" && item.Endpoint.Port > 0)
				{
					item.Response.Parameters[(byte)230] = new IPEndPoint(iPAddress, item.Endpoint.Port).ToString();
				}
				else
				{
					item.Avoid = true;
				}
			}
		}
	}
	[HarmonyPatch(typeof(LoadBalancingClient), "OnOperationResponse")]
	internal static class ServerSelection
	{
		private sealed class Attempt
		{
			internal int Retries;

			internal ulong SteamLobby;

			internal byte PendingOperation;
		}

		[HarmonyPatch(typeof(SteamLobbyManager), "OnLobbyCreated")]
		internal static class SteamCreation
		{
			[HarmonyPostfix]
			private static void Postfix(Result _result, Lobby _lobby)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Invalid comparison between Unknown and I4
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				if ((int)_result == 1)
				{
					freshSteamLobby = SteamId.op_Implicit(((Lobby)(ref _lobby)).Id);
				}
			}
		}

		[HarmonyPatch(typeof(MatchMakingCallbacksContainer), "OnJoinedRoom")]
		internal static class VoiceJoined
		{
			[HarmonyPrefix]
			private static void Prefix(LoadBalancingClient ___client)
			{
				//IL_0014: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Invalid comparison between Unknown and I4
				if (voiceRoom != null && voiceRoom == PhotonNetwork.CurrentRoom && (int)___client.Server == 1 && ___client.InRoom && !(___client.CurrentRoom.Name != voiceRoom.Name + "_voice_"))
				{
					PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
					if (!((Object)(object)existingInstance == (Object)null) && (object)((VoiceConnection)existingInstance).Client == ___client)
					{
						voiceAccepted = true;
						voiceNotice = null;
					}
				}
			}
		}

		private const int MaxPunRetries = 5;

		private const int MaxVoiceRetries = 1;

		private const double FreshLobbySeconds = 45.0;

		private static readonly ConditionalWeakTable<EnterRoomParams, Attempt> Attempts = new ConditionalWeakTable<EnterRoomParams, Attempt>();

		private static ulong freshSteamLobby;

		private static Room voiceRoom;

		private static bool voiceAccepted;

		private static LocalizedText? voiceNotice;

		private static float menuReadyAt;

		private static string VoiceTitle => Loc.Pick("Voice server avoided", "Сервер Voice пропущен");

		private static string Dismiss => Loc.Pick("OK", "ОК");

		[HarmonyPrefix]
		[HarmonyBefore(new string[] { "redos.justlatejoin" })]
		private static bool Prefix(LoadBalancingClient __instance, OperationResponse operationResponse, EnterRoomParams ___enterRoomParamsCache, bool __runOriginal)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Invalid comparison between Unknown and I4
			//IL_0025: 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_0033: Invalid comparison between Unknown and I4
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Invalid comparison between Unknown and I4
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Invalid comparison between Unknown and I4
			if (!__runOriginal || operationResponse == null || operationResponse.ReturnCode != 0)
			{
				return __runOriginal;
			}
			if ((int)__instance.Server == 1)
			{
				return CheckConnectedServer(__instance, ___enterRoomParamsCache, operationResponse);
			}
			if ((int)__instance.Server != 0 || (int)__instance.State != 8)
			{
				return true;
			}
			if (___enterRoomParamsCache == null || operationResponse.Parameters == null || !(operationResponse[(byte)230] is string text))
			{
				return true;
			}
			byte operationCode = operationResponse.OperationCode;
			if (__instance == PhotonNetwork.NetworkingClient)
			{
				if (operationCode != 227 && operationCode != 226)
				{
					return true;
				}
				Attempt value = Attempts.GetValue(___enterRoomParamsCache, (EnterRoomParams _) => new Attempt());
				if (operationCode == 226)
				{
					if ((int)___enterRoomParamsCache.JoinMode != 1)
					{
						return true;
					}
					if (value.SteamLobby == 0L)
					{
						if (freshSteamLobby == 0L || ___enterRoomParamsCache.RoomName != freshSteamLobby.ToString() || !OwnSteamLobby(freshSteamLobby))
						{
							return true;
						}
						value.SteamLobby = freshSteamLobby;
						freshSteamLobby = 0uL;
					}
				}
				return SelectPun(__instance, ___enterRoomParamsCache, value, text, operationResponse);
			}
			if (operationCode != 226 || (int)___enterRoomParamsCache.JoinMode != 1 || !LossMonitor.IsHosting)
			{
				return true;
			}
			PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
			Room currentRoom = PhotonNetwork.CurrentRoom;
			if ((Object)(object)existingInstance == (Object)null || (object)__instance != ((VoiceConnection)existingInstance).Client || currentRoom == null || ___enterRoomParamsCache.RoomName != currentRoom.Name + "_voice_")
			{
				return true;
			}
			if (voiceRoom != currentRoom)
			{
				ResetVoice(currentRoom);
			}
			if (voiceAccepted)
			{
				return true;
			}
			bool? flag = ServerOffer.IsAvoided(__instance, ___enterRoomParamsCache, operationResponse, text);
			if (!flag.HasValue)
			{
				return false;
			}
			Attempt value2 = Attempts.GetValue(___enterRoomParamsCache, (EnterRoomParams _) => new Attempt());
			if (!flag.Value)
			{
				value2.PendingOperation = operationCode;
				return true;
			}
			if (value2.Retries < 1)
			{
				value2.Retries++;
				if (RepeatReservation(__instance, ___enterRoomParamsCache, 226))
				{
					Plugin.Log.LogInfo((object)("Asking for a different Voice server after Photon offered " + text + "."));
					return false;
				}
			}
			StopVoice(existingInstance, currentRoom, text);
			return false;
		}

		private static void StopVoice(PunVoiceClient voice, Room room, string address)
		{
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			((VoiceFollowClient)voice).Disconnect();
			bool flag = CanLeaveFreshLobby(room);
			LocalizedText value = new LocalizedText("Photon offered an avoided Voice server (" + address + ")." + (flag ? "" : " Your voice chat is disconnected.") + " Create a new lobby to try another server.", "Photon предложил сервер Voice (" + address + ") из списка исключений." + (flag ? "" : " Ваш голосовой чат отключён.") + " Создайте новое лобби, чтобы попробовать другой сервер.");
			Plugin.Log.LogWarning((object)value.English);
			if (flag)
			{
				MenuManager.instance.PagePopUpScheduled(VoiceTitle, Color.yellow, value.Value, Dismiss, false);
				RunManager.instance.LeavePhotonRoom();
			}
			else
			{
				voiceNotice = value;
			}
		}

		private static bool CheckConnectedServer(LoadBalancingClient client, EnterRoomParams request, OperationResponse response)
		{
			if ((response.OperationCode != 230 && response.OperationCode != 231) || request == null || !Attempts.TryGetValue(request, out var value) || value.PendingOperation == 0)
			{
				return true;
			}
			byte pendingOperation = value.PendingOperation;
			value.PendingOperation = 0;
			string text = ServerEndpoint.Current(client);
			if (text == null || !Plugin.Avoided.Contains(text))
			{
				return true;
			}
			if (client != PhotonNetwork.NetworkingClient)
			{
				PunVoiceClient existingInstance = PunVoiceClient.ExistingInstance;
				if ((Object)(object)existingInstance == (Object)null || (object)client != ((VoiceConnection)existingInstance).Client || !LossMonitor.IsHosting || voiceRoom != PhotonNetwork.CurrentRoom || voiceAccepted)
				{
					return true;
				}
				StopVoice(existingInstance, voiceRoom, text);
				return false;
			}
			response.OperationCode = pendingOperation;
			return Reject(response, new LocalizedText("The assigned PUN endpoint resolved to avoided server " + text + ". Please create a new lobby.", "IP-адрес назначенного сервера PUN (" + text + ") входит в список исключений. Создайте новое лобби."));
		}

		private static bool CanLeaveFreshLobby(Room room)
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			RunManager instance = RunManager.instance;
			if (!LossMonitor.IsHosting || PhotonNetwork.CurrentRoom != room || room.PlayerCount != 1 || LossMonitor.HasHadGuests || Time.realtimeSinceStartupAsDouble - LossMonitor.HostedSince > 45.0 || !Object.op_Implicit((Object)(object)instance) || !Object.op_Implicit((Object)(object)MenuManager.instance) || instance.SceneHandoffActive || (int)instance.sessionLeaveState != 0)
			{
				return false;
			}
			if (!((Object)(object)Object.FindFirstObjectByType<NetworkConnect>() != (Object)null))
			{
				if (SemiFunc.RunIsLobbyMenu())
				{
					return !instance.restarting;
				}
				return false;
			}
			return true;
		}

		private static bool OwnSteamLobby(ulong id)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			SteamLobbyManager instance = SteamLobbyManager.instance;
			if ((Object)(object)instance != (Object)null && SteamClient.IsValid && SteamId.op_Implicit(((Lobby)(ref instance.currentLobby)).Id) == id)
			{
				return ((Lobby)(ref instance.currentLobby)).IsOwnedBy(SteamClient.SteamId);
			}
			return false;
		}

		private static bool SelectPun(LoadBalancingClient client, EnterRoomParams request, Attempt attempt, string address, OperationResponse response)
		{
			bool? flag = ServerOffer.IsAvoided(client, request, response, address);
			if (!flag.HasValue)
			{
				return false;
			}
			if (!flag.Value)
			{
				if (attempt.SteamLobby != 0L && attempt.Retries > 0 && (!OwnSteamLobby(attempt.SteamLobby) || !((Lobby)(ref SteamLobbyManager.instance.currentLobby)).SetData("RoomName", request.RoomName)))
				{
					return Reject(response, new LocalizedText("Could not publish the new private room name to Steam. Please create a new lobby.", "Не удалось обновить имя закрытого лобби в Steam. Создайте новое лобби."));
				}
				attempt.PendingOperation = response.OperationCode;
				return true;
			}
			if (attempt.Retries < 5 && (string.IsNullOrEmpty(request.RoomName) || attempt.SteamLobby != 0L))
			{
				attempt.Retries++;
				if (attempt.SteamLobby != 0L)
				{
					request.RoomName = attempt.SteamLobby + "-" + Guid.NewGuid().ToString("N");
				}
				if (RepeatReservation(client, request, response.OperationCode))
				{
					Plugin.Log.LogInfo((object)$"Avoiding PUN server {address}. Requesting another assignment ({attempt.Retries}/{5}).");
					return false;
				}
			}
			return Reject(response, new LocalizedText("Photon offered an avoided PUN server (" + address + "). Please create a new lobby.", "Photon предложил сервер PUN (" + address + ") из списка исключений. Создайте новое лобби."));
		}

		private static bool RepeatReservation(LoadBalancingClient client, EnterRoomParams request, byte operation)
		{
			try
			{
				return (operation == 227) ? client.LoadBalancingPeer.OpCreateRoom(request) : client.LoadBalancingPeer.OpJoinRoom(request);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not request another Photon server: " + ex.Message));
				return false;
			}
		}

		private static bool Reject(OperationResponse response, LocalizedText notice)
		{
			response.ReturnCode = -1;
			response.DebugMessage = notice.Value;
			Plugin.Log.LogWarning((object)notice.English);
			return true;
		}

		private static void ResetVoice(Room room)
		{
			voiceRoom = room;
			voiceAccepted = false;
			voiceNotice = null;
			menuReadyAt = 0f;
		}

		internal static void Tick()
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Invalid comparison between Unknown and I4
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			if (voiceRoom == null)
			{
				return;
			}
			if (voiceRoom != PhotonNetwork.CurrentRoom || !LossMonitor.IsHosting)
			{
				ResetVoice(null);
				return;
			}
			LocalizedText? localizedText = voiceNotice;
			if (!localizedText.HasValue)
			{
				return;
			}
			LocalizedText valueOrDefault = localizedText.GetValueOrDefault();
			if (SemiFunc.RunIsLobbyMenu())
			{
				MenuManager instance = MenuManager.instance;
				if ((Object)(object)instance == (Object)null || !Object.op_Implicit((Object)(object)instance.currentMenuPage) || !Object.op_Implicit((Object)(object)LevelGenerator.Instance) || !LevelGenerator.Instance.Generated)
				{
					menuReadyAt = 0f;
					return;
				}
				if (menuReadyAt == 0f)
				{
					menuReadyAt = Time.realtimeSinceStartup + 2f;
				}
				if (Time.realtimeSinceStartup < menuReadyAt)
				{
					return;
				}
				instance.PagePopUp(VoiceTitle, Color.yellow, valueOrDefault.Value, Dismiss, false);
			}
			else
			{
				if (!Object.op_Implicit((Object)(object)MissionUI.instance) || !Object.op_Implicit((Object)(object)GameDirector.instance) || (int)GameDirector.instance.currentState != 2 || SemiFunc.MenuLevel())
				{
					return;
				}
				SemiFunc.UIFocusText(valueOrDefault.Value, Color.white, Color.yellow, 8f);
			}
			voiceNotice = null;
		}
	}
}