Decompiled source of RoundsLanPhoton v0.8.0

BepInEx/plugins/RoundsLanPhoton.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Tiago Al Tabaa")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Points ROUNDS at a Photon server on your own LAN.")]
[assembly: AssemblyFileVersion("0.8.0.0")]
[assembly: AssemblyInformationalVersion("0.8.0+cbd49b0008e7eb00b593d7bcd887cbeb17ccfd7f")]
[assembly: AssemblyProduct("ROUNDS LAN Photon")]
[assembly: AssemblyTitle("RoundsLanPhoton")]
[assembly: AssemblyVersion("0.8.0.0")]
namespace RoundsLanPhoton;

[BepInPlugin("tiago.rounds.lanphoton", "ROUNDS LAN Photon", "0.8.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Guid = "tiago.rounds.lanphoton";

	public const string PluginVersion = "0.8.0";

	internal static bool ForceGameServer = false;

	internal static ManualLogSource Log;

	internal static string LanRoomName = "rounds-lan";

	internal static bool LanBusy;

	internal static string LanStatus = "";

	internal static readonly LanSession Session = new LanSession();

	internal static readonly SettingsSnapshot Snapshot = new SettingsSnapshot();

	internal static ConfigEntry<bool> RedirectGameConnects;

	internal static ConfigEntry<bool> Enabled;

	internal static ConfigEntry<string> Address;

	internal static ConfigEntry<int> Port;

	internal static ConfigEntry<string> AppId;

	internal static ConfigEntry<bool> ForceBinaryV16;

	internal static ConfigEntry<string> Protocol;

	internal static ConfigEntry<float> EnforceSeconds;

	internal static ConfigEntry<bool> ReconDump;

	internal static ConfigEntry<string> ReconTypes;

	internal static ConfigEntry<string> DiscoveryMode;

	internal static ConfigEntry<int> DiscoveryPort;

	internal static ConfigEntry<float> DiscoveryTimeout;

	internal static ConfigEntry<string> AdvertiseAddress;

	internal static ConfigEntry<bool> UiEnabled;

	internal static ConfigEntry<string> UiToggleKey;

	internal static ConfigEntry<float> UiWidth;

	internal static ConfigEntry<bool> UiShowOnStart;

	internal static ConfigEntry<bool> UiShowButton;

	internal static ConfigEntry<string> UiStyle;

	internal static ConfigEntry<string> ServerPath;

	internal static ConfigEntry<string> AutoHost;

	internal static ConfigEntry<float> AutoHostDelay;

	internal static ConfigEntry<bool> SelfTest;

	private LanDiscovery _discovery;

	private bool _serverFound;

	private bool _uiVisible;

	private KeyCode _toggleKey = (KeyCode)289;

	internal static Plugin Instance;

	private bool _inputWarned;

	private bool _guiWarned;

	private float _lastEnforceTick;

	private static bool _leaving;

	internal static bool Redirecting
	{
		get
		{
			if (Enabled == null || !Enabled.Value)
			{
				return false;
			}
			if (Session.Redirecting)
			{
				return true;
			}
			if (RedirectGameConnects != null)
			{
				return RedirectGameConnects.Value;
			}
			return false;
		}
	}

	internal LanDiscovery Discovery => _discovery;

	internal string PluginVersionString => "0.8.0";

	internal static bool NativeStyle
	{
		get
		{
			if (UiStyle != null)
			{
				return !string.Equals((UiStyle.Value ?? "").Trim(), "overlay", StringComparison.OrdinalIgnoreCase);
			}
			return true;
		}
	}

	private void Awake()
	{
		Instance = this;
		try
		{
			AwakeCore();
		}
		catch (Exception ex)
		{
			Log.LogError((object)("[LAN] startup failed, the plugin is inert until this is fixed: " + ex));
		}
	}

	private void AwakeCore()
	{
		//IL_0433: Unknown result type (might be due to invalid IL or missing references)
		//IL_0438: 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, "Master switch. When off, the plugin loads and logs but changes nothing.");
		RedirectGameConnects = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RedirectGameConnects", false, "Off (recommended): only a LAN Host or Join rewrites Photon, so the game's own ONLINE screen keeps working. On: 0.7.0 behaviour, every connect the game makes is redirected, which leaves the game hanging on its loading screen when no LAN server is running.");
		Address = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "Address", "127.0.0.1", "IP or hostname of the Photon server on your LAN.");
		Port = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "Port", 5055, "Photon server master port. The on-premises default is 5055.");
		AppId = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "AppIdRealtime", "", "Leave empty to keep whatever AppId the game sets. Set it only if your Photon application requires a specific one.");
		ForceBinaryV16 = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "ForceGpBinaryV16", false, "Obsolete since 0.5.0 and ignored: SerializationProtocol below decides.");
		Protocol = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "SerializationProtocol", "V18", "V18 (default) or V16. PUN forces V16 whenever it dials a master server directly, but RoundsWithFriends sends a custom-type array in player properties, and the LAN server only parses that correctly in V18. Measured: V16 left the host stuck in Joining.");
		EnforceSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Tuning", "EnforceEverySeconds", 1f, "Re-apply the settings this often while the plugin is enabled. 0 disables the loop.");
		ReconDump = ((BaseUnityPlugin)this).Config.Bind<bool>("Tuning", "ReconDump", true, "On startup, write the networking API of the game (type and method names) into the BepInEx log. This is what lets us hook deeper paths, including the Steam lobby.");
		ReconTypes = ((BaseUnityPlugin)this).Config.Bind<string>("Tuning", "ReconTypeFilters", "iLandfall.Network,NetworkConnectionHandler,Lobby,PhotonNetwork,ServerSettings,MenuPage,MainMenu,OnlineMenu,LocalMenu,MenuButton,MenuScreen", "Comma-separated substrings of type names to dump when ReconDump is on. The menu entries are what a native LAN section has to be built from.");
		DiscoveryMode = ((BaseUnityPlugin)this).Config.Bind<string>("Discovery", "Mode", "auto", "auto = find the Photon server on the LAN by itself (recommended); host = this machine runs the Photon server and advertises it to the others; manual = use the Address below and do no discovery.");
		DiscoveryPort = ((BaseUnityPlugin)this).Config.Bind<int>("Discovery", "Port", 47777, "UDP port used for discovery. Must be the same on every machine.");
		DiscoveryTimeout = ((BaseUnityPlugin)this).Config.Bind<float>("Discovery", "TimeoutSeconds", 15f, "In auto mode, how long to listen for the host before falling back to the Address below.");
		AdvertiseAddress = ((BaseUnityPlugin)this).Config.Bind<string>("Discovery", "AdvertiseAddress", "", "Host mode only, leave blank to advertise this machine's own LAN address.");
		UiEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Panel", "Enabled", true, "The in-game LAN panel (drawn over the game by this plugin).");
		UiToggleKey = ((BaseUnityPlugin)this).Config.Bind<string>("Panel", "ToggleKey", "F8", "Key that shows and hides the panel.");
		UiWidth = ((BaseUnityPlugin)this).Config.Bind<float>("Panel", "Width", 460f, "Panel width in pixels.");
		UiShowOnStart = ((BaseUnityPlugin)this).Config.Bind<bool>("Panel", "ShowOnStart", true, "Show the panel as soon as the game starts. On by default so the panel proves itself without depending on a key press; set it to false once you are happy.");
		UiStyle = ((BaseUnityPlugin)this).Config.Bind<string>("Panel", "Style", "native", "native (default): LAN lives in the game's own main menu, beside ONLINE, and this debug panel stays hidden until F8. overlay: the old behaviour, panel and corner button as below. If the native page cannot be added, the panel comes back by itself.");
		UiShowButton = ((BaseUnityPlugin)this).Config.Bind<bool>("Panel", "ShowButton", true, "Draw a small LAN button in the corner while the panel is hidden, so it can be opened with the mouse even if the keyboard toggle does not work on this machine.");
		ServerPath = ((BaseUnityPlugin)this).Config.Bind<string>("Host", "ServerPath", "", "Where the LAN server (luxon_server.exe) lives on the hosting PC. Empty = %LOCALAPPDATA%\\RoundsLan\\luxon\\luxon_server.exe, which is where Setup-Host.ps1 puts it.");
		AutoHost = ((BaseUnityPlugin)this).Config.Bind<string>("Host", "AutoHostRoom", "", "Testing aid: when set, this PC hosts a LAN room with this name by itself shortly after the main menu loads, exactly as if Host had been clicked. Leave empty for normal play.");
		SelfTest = ((BaseUnityPlugin)this).Config.Bind<bool>("Host", "SelfTest", false, "Testing only. After AutoHostRoom opens, presses Host again, Join on the same room, then Host on a second room, and logs each result as '[LAN] selftest'. Leave off.");
		AutoHostDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Host", "AutoHostDelaySeconds", 30f, "How long after start the AutoHostRoom fires, so the menu and Photon are up first.");
		ApplyDiscoverySettingsToServer();
		int num = HarmonyPatcher.PatchAll();
		Log.LogInfo((object)string.Format("[LAN] ROUNDS LAN Photon {0} | enabled={1} server={2}:{3} | redirect={4} | harmony patches={5}", "0.8.0", Enabled.Value, Address.Value, Port.Value, RedirectGameConnects.Value ? "every connect (0.7.0 mode)" : "only a LAN host or join", num));
		if (ReconDump.Value)
		{
			Recon.Run(ReconTypes.Value.Split(new char[1] { ',' }));
		}
		_uiVisible = !NativeStyle && UiShowOnStart.Value;
		try
		{
			_toggleKey = (KeyCode)Enum.Parse(typeof(KeyCode), UiToggleKey.Value.Trim(), ignoreCase: true);
		}
		catch
		{
			Log.LogWarning((object)("[LAN] could not parse ToggleKey '" + UiToggleKey.Value + "', using F8"));
		}
		Log.LogInfo((object)string.Format("[LAN] panel: enabled={0} visible={1} key={2} | config file: {3}", UiEnabled.Value, _uiVisible, UiToggleKey.Value, ((BaseUnityPlugin)this).Config.ConfigFilePath ?? "(unknown)"));
		StartDiscovery();
		LanMenuPage.Install(this);
		((MonoBehaviour)this).Invoke("FontReport", 20f);
		if (EnforceSeconds.Value > 0f)
		{
			((MonoBehaviour)this).InvokeRepeating("EnforceTick", 5f, EnforceSeconds.Value);
		}
		if (!string.IsNullOrEmpty(AutoHost.Value))
		{
			Log.LogInfo((object)("[LAN] AutoHostRoom='" + AutoHost.Value + "': hosting by itself in " + AutoHostDelay.Value + "s"));
			((MonoBehaviour)this).Invoke("AutoHostTick", AutoHostDelay.Value);
		}
		else if (SelfTest.Value)
		{
			Log.LogInfo((object)("[LAN] SelfTest without AutoHostRoom: opening the LAN page in " + AutoHostDelay.Value + "s"));
			((MonoBehaviour)this).Invoke("SelfTestOpenLanPage", AutoHostDelay.Value);
		}
	}

	public void AutoHostTick()
	{
		LanRoomName = AutoHost.Value;
		LanRooms.Host(AutoHost.Value, delegate(bool? ok, string msg)
		{
			LanStatus = ((ok == true) ? "OK: " : ((ok == false) ? "FAILED: " : "")) + msg;
			Log.LogInfo((object)("[LAN] autohost -> " + LanStatus));
			if (ok == true && SelfTest.Value)
			{
				((MonoBehaviour)this).Invoke("SelfTestStep1", 5f);
			}
		});
	}

	private void SelfTestCall(string step, bool host, string room, string next)
	{
		object target = PhotonReflection.GetStatic(PhotonReflection.PhotonNetworkType, "CurrentRoom");
		Log.LogInfo((object)("[LAN] selftest " + step + ": " + (host ? "Host" : "Join") + " '" + room + "'  (before: in room '" + (PhotonReflection.Get(target, "Name") ?? "none")?.ToString() + "', players " + (PhotonReflection.Get(target, "PlayerCount") ?? "-")?.ToString() + ")"));
		LanRooms.Report report = delegate(bool? ok, string msg)
		{
			Log.LogInfo((object)("[LAN] selftest " + step + " -> " + ((ok == true) ? "OK: " : ((ok == false) ? "FAILED: " : "... ")) + msg));
			if (ok.HasValue && next != null)
			{
				((MonoBehaviour)this).Invoke(next, 5f);
			}
		};
		if (host)
		{
			LanRooms.Host(room, report);
		}
		else
		{
			LanRooms.Join(room, report);
		}
	}

	public void SelfTestStep1()
	{
		SelfTestCall("1 (Host again, same room)", host: true, AutoHost.Value, "SelfTestStep2");
	}

	public void SelfTestStep2()
	{
		SelfTestCall("2 (Join, same room, on the host)", host: false, AutoHost.Value, "SelfTestStep3");
	}

	public void SelfTestStep3()
	{
		SelfTestCall("3 (Host a different room)", host: true, AutoHost.Value + "-b", "SelfTestStep4");
	}

	public void SelfTestStep4()
	{
		SelfTestCall("4 (Host the first room again)", host: true, AutoHost.Value, "SelfTestStep5");
	}

	public void SelfTestOpenLanPage()
	{
		Log.LogInfo((object)("[LAN] selftest: LAN page " + (LanMenuPage.OpenForTest() ? "open" : "NOT open") + ", overlay visible=" + _uiVisible));
	}

	public void SelfTestStep5()
	{
		object target = PhotonReflection.GetStatic(PhotonReflection.PhotonNetworkType, "CurrentRoom");
		Log.LogInfo((object)("[LAN] selftest 5 (still there 5 s later?): in room '" + (PhotonReflection.Get(target, "Name") ?? "none")?.ToString() + "'"));
	}

	internal bool BecomeHost()
	{
		bool flag = Address.Value != "127.0.0.1";
		if (flag)
		{
			Address.Value = "127.0.0.1";
		}
		string text = LocalServer.BestLanAddress();
		if (_discovery != null && _discovery.IsBeacon && _discovery.IsRunning)
		{
			return flag;
		}
		try
		{
			if (_discovery != null)
			{
				_discovery.Stop();
				_discovery = null;
			}
		}
		catch
		{
		}
		_discovery = new LanDiscovery(DiscoveryPort.Value, beacon: true, text, Port.Value, (Action<string, int>)null, (Action<string>)Log.LogInfo);
		_discovery.Start();
		Log.LogInfo((object)("[LAN] hosting: this PC is the server, advertised as " + text + ":" + Port.Value));
		return flag;
	}

	private void StartDiscovery()
	{
		switch ((DiscoveryMode.Value ?? "auto").Trim().ToLowerInvariant())
		{
		case "manual":
		case "off":
		case "none":
			Log.LogInfo((object)("[LAN] discovery off; every client uses " + Address.Value + ":" + Port.Value));
			break;
		case "host":
		{
			string text = AdvertiseAddress.Value;
			if (string.IsNullOrEmpty(text))
			{
				text = LocalAddress();
			}
			_discovery = new LanDiscovery(DiscoveryPort.Value, beacon: true, text, Port.Value, (Action<string, int>)null, (Action<string>)Log.LogInfo);
			_discovery.Start();
			Log.LogInfo((object)("[LAN] this machine advertises itself as the Photon server: " + text + ":" + Port.Value));
			break;
		}
		default:
			_discovery = new LanDiscovery(DiscoveryPort.Value, beacon: false, "", Port.Value, (Action<string, int>)OnServerFound, (Action<string>)Log.LogInfo);
			_discovery.Start();
			((MonoBehaviour)this).Invoke("DiscoveryWatchdog", DiscoveryTimeout.Value);
			break;
		}
	}

	private void OnServerFound(string address, int port)
	{
		if (address == Address.Value && port == Port.Value)
		{
			_serverFound = true;
			return;
		}
		Address.Value = address;
		Port.Value = port;
		_serverFound = true;
		Log.LogInfo((object)("[LAN] using the discovered server " + address + ":" + port + " (written to the config file too)"));
	}

	public void DiscoveryWatchdog()
	{
		if (!_serverFound)
		{
			Log.LogWarning((object)("[LAN] no Photon server answered on udp/" + DiscoveryPort.Value + " within " + DiscoveryTimeout.Value + "s. Still listening, and falling back to " + Address.Value + ":" + Port.Value + " for now. If the host is up, check that both machines are on the same network and that Windows Firewall allows udp/" + DiscoveryPort.Value + " inbound."));
		}
	}

	private static string LocalAddress()
	{
		try
		{
			NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
			foreach (NetworkInterface networkInterface in allNetworkInterfaces)
			{
				if (networkInterface.OperationalStatus != OperationalStatus.Up || networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback)
				{
					continue;
				}
				foreach (UnicastIPAddressInformation unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
				{
					if (unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork)
					{
						string text = unicastAddress.Address.ToString();
						if (!text.StartsWith("169.254."))
						{
							return text;
						}
					}
				}
			}
		}
		catch
		{
		}
		return "";
	}

	private void ApplyDiscoverySettingsToServer()
	{
		if (Port.Value <= 0)
		{
			Port.Value = 5055;
		}
	}

	private void OnDestroy()
	{
		try
		{
			if (_discovery != null)
			{
				_discovery.Stop();
			}
		}
		catch
		{
		}
		LocalServer.StopIfOurs();
	}

	private void OnApplicationQuit()
	{
		LocalServer.StopIfOurs();
	}

	internal void LogLine(string message)
	{
		Log.LogInfo((object)("[LAN] " + message));
	}

	internal void NativeMenuUnavailable()
	{
		if (NativeStyle)
		{
			_uiVisible = UiShowOnStart.Value;
			LogLine("native menu unavailable, showing the panel instead");
		}
	}

	internal void SetPanelVisible(bool visible)
	{
		_uiVisible = visible;
		LogLine("panel " + (visible ? "shown" : "hidden"));
	}

	public void FontReport()
	{
		try
		{
			Overlay.GameFont();
			Overlay.ReportFontSystem();
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("[LAN] font report failed: " + ex.Message));
		}
		try
		{
			MenuProbe.Run();
		}
		catch (Exception ex2)
		{
			Log.LogWarning((object)("[LAN] menu probe failed: " + ex2.Message));
		}
	}

	internal string AdvertisedAddress()
	{
		string value = AdvertiseAddress.Value;
		if (!string.IsNullOrEmpty(value))
		{
			return value;
		}
		return LocalAddress();
	}

	internal List<string> LocalAddresses()
	{
		List<string> list = new List<string>();
		try
		{
			NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
			foreach (NetworkInterface networkInterface in allNetworkInterfaces)
			{
				if (networkInterface.OperationalStatus != OperationalStatus.Up || networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback)
				{
					continue;
				}
				foreach (UnicastIPAddressInformation unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
				{
					if (unicastAddress.Address.AddressFamily == AddressFamily.InterNetwork)
					{
						string text = unicastAddress.Address.ToString();
						if (!text.StartsWith("169.254."))
						{
							list.Add(text + "   (" + networkInterface.Name + ")");
						}
					}
				}
			}
		}
		catch
		{
		}
		if (list.Count == 0)
		{
			list.Add("(no IPv4 address found)");
		}
		return list;
	}

	internal void RestartDiscovery()
	{
		try
		{
			if (_discovery != null)
			{
				_discovery.Stop();
				_discovery = null;
			}
		}
		catch
		{
		}
		_serverFound = false;
		StartDiscovery();
		LogLine("discovery restarted");
	}

	private void Update()
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		if (!UiEnabled.Value)
		{
			return;
		}
		try
		{
			if (Input.GetKeyDown(_toggleKey))
			{
				_uiVisible = !_uiVisible;
				LogLine("panel " + (_uiVisible ? "shown" : "hidden"));
			}
		}
		catch (Exception ex)
		{
			if (!_inputWarned)
			{
				_inputWarned = true;
				Log.LogWarning((object)("[LAN] legacy keyboard API unavailable (" + ex.GetType().Name + "); use the LAN button in the corner or Panel.ShowOnStart = true"));
			}
		}
	}

	private void OnGUI()
	{
		//IL_0078: Unknown result type (might be due to invalid IL or missing references)
		//IL_007e: Invalid comparison between Unknown and I4
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Unknown result type (might be due to invalid IL or missing references)
		//IL_004b: Unknown result type (might be due to invalid IL or missing references)
		if (!UiEnabled.Value)
		{
			return;
		}
		try
		{
			if (!_uiVisible && UiShowButton.Value && (!NativeStyle || !LanMenuPage.Installed) && GUI.Button(new Rect((float)Screen.width - 62f, 8f, 54f, 22f), "LAN"))
			{
				_uiVisible = true;
				LogLine("panel opened with the mouse");
			}
			Event current = Event.current;
			if (current != null && (int)current.type == 4 && current.keyCode == _toggleKey)
			{
				_uiVisible = !_uiVisible;
				LogLine("panel " + (_uiVisible ? "shown" : "hidden") + " by " + ((object)Unsafe.As<KeyCode, KeyCode>(ref _toggleKey)/*cast due to .constrained prefix*/).ToString());
				current.Use();
			}
			if (_uiVisible)
			{
				Overlay.Draw(this);
			}
		}
		catch (Exception ex)
		{
			if (!_guiWarned)
			{
				_guiWarned = true;
				Log.LogWarning((object)("[LAN] panel draw failed: " + ex));
			}
		}
	}

	public void EnforceTick()
	{
		if (Enabled == null || !Enabled.Value)
		{
			return;
		}
		try
		{
			Type photonNetworkType = PhotonReflection.PhotonNetworkType;
			bool flag = photonNetworkType != null && GetBool(photonNetworkType, "OfflineMode");
			bool flag2 = photonNetworkType != null && GetBool(photonNetworkType, "InRoom") && !flag;
			bool flag3 = photonNetworkType != null && ClientConnecting(photonNetworkType);
			if (Session.Redirecting)
			{
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				float deltaSeconds = ((_lastEnforceTick > 0f) ? (realtimeSinceStartup - _lastEnforceTick) : 0f);
				_lastEnforceTick = realtimeSinceStartup;
				if (Session.Observe(deltaSeconds, flag2, flag3) == LanWatch.Restore)
				{
					Log.LogInfo((object)"[LAN] the LAN room is gone and the client is idle: putting the game's own Photon settings back");
					RecoverNow("the LAN room ended");
				}
				else if (!flag2 || flag3)
				{
					Settings.Apply("enforcer", verbose: false);
				}
			}
			else if (Session.RestorePending)
			{
				RecoverNow("a LAN attempt ended");
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("[LAN] enforcement tick failed: " + ex.Message));
		}
	}

	private static bool ClientConnecting(Type pn)
	{
		if (!GetBool(pn, "IsConnected"))
		{
			return false;
		}
		if (GetBool(pn, "OfflineMode"))
		{
			return false;
		}
		return !GetBool(pn, "InRoom");
	}

	private static bool GetBool(Type t, string name)
	{
		object obj = PhotonReflection.GetStatic(t, name);
		bool flag = default(bool);
		int num;
		if (obj is bool)
		{
			flag = (bool)obj;
			num = 1;
		}
		else
		{
			num = 0;
		}
		return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
	}

	internal static void RecoverNow(string why)
	{
		try
		{
			Type photonNetworkType = PhotonReflection.PhotonNetworkType;
			if (photonNetworkType != null && GetBool(photonNetworkType, "InRoom") && !GetBool(photonNetworkType, "OfflineMode"))
			{
				if ((Object)(object)Instance != (Object)null && !_leaving)
				{
					((MonoBehaviour)Instance).StartCoroutine(Instance.CoLeaveLan(why));
					return;
				}
				if ((Object)(object)Instance == (Object)null)
				{
					CallStaticBool(photonNetworkType, "LeaveRoom", new Type[1] { typeof(bool) }, new object[1] { false });
				}
			}
			FinishRecovery(why);
		}
		catch (Exception ex)
		{
			if (Log != null)
			{
				Log.LogWarning((object)("[LAN] recovery failed: " + ex.Message));
			}
		}
	}

	private static void FinishRecovery(string why)
	{
		try
		{
			Type photonNetworkType = PhotonReflection.PhotonNetworkType;
			if (photonNetworkType != null)
			{
				if (GetBool(photonNetworkType, "IsConnected") && !GetBool(photonNetworkType, "OfflineMode"))
				{
					CallStaticBool(photonNetworkType, "Disconnect", Type.EmptyTypes, null);
				}
				SetOffline(photonNetworkType);
			}
			Settings.Restore();
			Session.Restored();
			LanStatus = "LAN session ended (" + why + "): the game is back on its own settings";
			if (Log != null)
			{
				Log.LogInfo((object)("[LAN] " + LanStatus));
			}
		}
		catch (Exception ex)
		{
			if (Log != null)
			{
				Log.LogWarning((object)("[LAN] recovery failed: " + ex.Message));
			}
		}
	}

	private static void SetOffline(Type pn)
	{
		try
		{
			Type type = PhotonReflection.FindType("SetOfflineMode");
			if (type != null)
			{
				Object val = Object.FindObjectOfType(type);
				MethodInfo method = type.GetMethod("SetOffline", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
				if (val != (Object)null && method != null)
				{
					method.Invoke(val, null);
					return;
				}
			}
		}
		catch (Exception ex)
		{
			if (Log != null)
			{
				Log.LogWarning((object)("[LAN] the game's SetOfflineMode was not usable: " + ex.Message));
			}
		}
		try
		{
			if (pn != null)
			{
				PhotonReflection.Set(pn, "OfflineMode", true, isStatic: true);
			}
		}
		catch
		{
		}
	}

	private static object CallStaticBool(Type t, string name, Type[] types, object[] args)
	{
		try
		{
			MethodInfo method = t.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, types, null);
			if (method == null)
			{
				return null;
			}
			return method.Invoke(null, args);
		}
		catch (Exception ex)
		{
			if (Log != null)
			{
				Log.LogWarning((object)("[LAN] " + name + " failed: " + ex.Message));
			}
			return null;
		}
	}

	public void LeaveLan()
	{
		if (!((Object)(object)Instance == (Object)null))
		{
			((MonoBehaviour)this).StartCoroutine(CoLeaveLan("the player asked to leave"));
		}
	}

	private IEnumerator CoLeaveLan(string why)
	{
		_leaving = true;
		LanBusy = true;
		try
		{
			Type photonNetworkType = PhotonReflection.PhotonNetworkType;
			if (photonNetworkType != null && GetBool(photonNetworkType, "InRoom") && !GetBool(photonNetworkType, "OfflineMode"))
			{
				yield return LanRooms.GameRestart(photonNetworkType);
			}
			Session.Left();
		}
		finally
		{
			_leaving = false;
			LanBusy = false;
		}
		FinishRecovery(why);
	}
}
internal static class PhotonReflection
{
	private static Type _photonNetwork;

	private static Type _appSettings;

	private static bool _resolved;

	internal static Type PhotonNetworkType
	{
		get
		{
			if (!_resolved)
			{
				_resolved = true;
				_photonNetwork = FindType("Photon.Pun.PhotonNetwork") ?? FindType("PhotonNetwork") ?? FindType("Photon.Pun.PhotonHandler");
				_appSettings = FindType("Photon.Realtime.AppSettings") ?? FindType("ExitGames.Client.Photon.AppSettings");
				Plugin.Log.LogInfo((object)string.Format("[LAN] resolved PhotonNetwork={0} AppSettings={1}", (_photonNetwork == null) ? "NOT FOUND" : _photonNetwork.Assembly.GetName().Name, (_appSettings == null) ? "NOT FOUND" : _appSettings.Assembly.GetName().Name));
			}
			return _photonNetwork;
		}
	}

	internal static Type AppSettingsType
	{
		get
		{
			_ = PhotonNetworkType;
			return _appSettings;
		}
	}

	internal static Type FindType(string fullName)
	{
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			try
			{
				Type type = assembly.GetType(fullName, throwOnError: false);
				if (type != null)
				{
					return type;
				}
			}
			catch
			{
			}
		}
		string text = (fullName.StartsWith("Photon.Pun") ? "PhotonUnityNetworking" : (fullName.StartsWith("Photon.Realtime") ? "PhotonRealtime" : (fullName.StartsWith("ExitGames") ? "Photon3Unity3D" : null)));
		if (text != null)
		{
			try
			{
				return Assembly.Load(text).GetType(fullName, throwOnError: false);
			}
			catch
			{
			}
		}
		return null;
	}

	internal static object GetStatic(object target, string name)
	{
		return Get(target, name, isStatic: true);
	}

	internal static object Get(object target, string name, bool isStatic = false)
	{
		if (target == null)
		{
			return null;
		}
		Type type = (isStatic ? ((Type)target) : target.GetType());
		try
		{
			PropertyInfo property = type.GetProperty(name, (BindingFlags)(0x30 | (isStatic ? 8 : 4)));
			if (property != null && property.CanRead)
			{
				return property.GetValue(isStatic ? null : target, null);
			}
			FieldInfo field = type.GetField(name, (BindingFlags)(0x30 | (isStatic ? 8 : 4)));
			if (field != null)
			{
				return field.GetValue(isStatic ? null : target);
			}
		}
		catch
		{
		}
		return null;
	}

	internal static bool Set(object target, string name, object value, bool isStatic = false)
	{
		if (target == null)
		{
			return false;
		}
		Type type = (isStatic ? ((Type)target) : target.GetType());
		try
		{
			FieldInfo field = type.GetField(name, (BindingFlags)(0x30 | (isStatic ? 8 : 4)));
			if (field != null)
			{
				field.SetValue(isStatic ? null : target, Coerce(field.FieldType, value));
				return true;
			}
			PropertyInfo property = type.GetProperty(name, (BindingFlags)(0x30 | (isStatic ? 8 : 4)));
			if (property != null && property.CanWrite)
			{
				property.SetValue(isStatic ? null : target, Coerce(property.PropertyType, value), null);
				return true;
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)$"[LAN] could not set {name}: {ex.Message}");
		}
		return false;
	}

	private static object Coerce(Type target, object value)
	{
		if (value == null)
		{
			return null;
		}
		if (target.IsInstanceOfType(value))
		{
			return value;
		}
		if (target.IsEnum && value is string)
		{
			return Enum.Parse(target, (string)value, ignoreCase: true);
		}
		try
		{
			return Convert.ChangeType(value, target);
		}
		catch
		{
			return value;
		}
	}
}
internal static class Settings
{
	internal static void Apply(string why, bool verbose = true)
	{
		if (!Plugin.Redirecting)
		{
			if (verbose)
			{
				Plugin.Log.LogInfo((object)("[LAN] not applying (" + why + "): no LAN session is active"));
			}
			return;
		}
		Type photonNetworkType = PhotonReflection.PhotonNetworkType;
		if (photonNetworkType == null)
		{
			Plugin.Log.LogWarning((object)("[LAN] PhotonNetwork type not found; nothing to patch (" + why + ")"));
			return;
		}
		object obj = PhotonReflection.GetStatic(photonNetworkType, "PhotonServerSettings");
		object obj2 = ((obj != null) ? PhotonReflection.Get(obj, "AppSettings") : null);
		if (obj2 == null)
		{
			Plugin.Log.LogWarning((object)("[LAN] AppSettings object not found (" + why + ")"));
			return;
		}
		Capture(obj2);
		bool flag = PhotonReflection.Set(obj2, "Server", Plugin.Address.Value);
		bool flag2 = PhotonReflection.Set(obj2, "Port", Plugin.Port.Value);
		bool flag3 = PhotonReflection.Set(obj2, "UseNameServer", false);
		bool flag4 = PhotonReflection.Set(obj2, "FixedRegion", "");
		bool flag5 = true;
		if (!string.IsNullOrEmpty(Plugin.AppId.Value))
		{
			flag5 = PhotonReflection.Set(obj2, "AppIdRealtime", Plugin.AppId.Value);
		}
		try
		{
			object obj3 = PhotonReflection.GetStatic(photonNetworkType, "NetworkingClient");
			if (obj3 != null)
			{
				PropertyInfo property = obj3.GetType().GetProperty("SerializationProtocol");
				if (property != null)
				{
					Type propertyType = property.PropertyType;
					string text = HarmonyPatcher.WantedProtocolName(propertyType);
					if (text != null)
					{
						property.SetValue(obj3, Enum.Parse(propertyType, text), null);
					}
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] protocol set failed: " + ex.Message));
		}
		if (verbose)
		{
			Plugin.Log.LogInfo((object)string.Format("[LAN] applied ({0}): Server={1} Port={2} UseNameServer=false AppId={3} sets={4}{5}{6}{7}", why, Plugin.Address.Value, Plugin.Port.Value, string.IsNullOrEmpty(Plugin.AppId.Value) ? "(game default)" : Plugin.AppId.Value, flag, flag2, flag3, flag4, flag5));
		}
	}

	private static void Capture(object appSettings)
	{
		if (Plugin.Snapshot.Captured)
		{
			return;
		}
		try
		{
			string server = PhotonReflection.Get(appSettings, "Server") as string;
			string appIdRealtime = PhotonReflection.Get(appSettings, "AppIdRealtime") as string;
			string fixedRegion = PhotonReflection.Get(appSettings, "FixedRegion") as string;
			object v = PhotonReflection.Get(appSettings, "Port");
			object obj = PhotonReflection.Get(appSettings, "UseNameServer");
			SettingsSnapshot snapshot = Plugin.Snapshot;
			int port = ToInt(v);
			bool flag = default(bool);
			int num;
			if (obj is bool)
			{
				flag = (bool)obj;
				num = 1;
			}
			else
			{
				num = 0;
			}
			if (snapshot.Take(server, port, (byte)((uint)num & (flag ? 1u : 0u)) != 0, appIdRealtime, fixedRegion))
			{
				Plugin.Log.LogInfo((object)("[LAN] saved the game's own settings for later: " + Plugin.Snapshot.Summary()));
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] could not save the game's settings: " + ex.Message));
		}
	}

	internal static void Restore()
	{
		if (!Plugin.Snapshot.Captured)
		{
			Plugin.Log.LogInfo((object)"[LAN] nothing to restore: the game's settings were never replaced");
			return;
		}
		try
		{
			Type photonNetworkType = PhotonReflection.PhotonNetworkType;
			object obj = ((photonNetworkType == null) ? null : PhotonReflection.GetStatic(photonNetworkType, "PhotonServerSettings"));
			object obj2 = ((obj != null) ? PhotonReflection.Get(obj, "AppSettings") : null);
			if (obj2 == null)
			{
				Plugin.Log.LogWarning((object)"[LAN] AppSettings is gone; cannot write the saved values back");
				return;
			}
			PhotonReflection.Set(obj2, "Server", Plugin.Snapshot.Server);
			PhotonReflection.Set(obj2, "Port", Plugin.Snapshot.Port);
			PhotonReflection.Set(obj2, "UseNameServer", Plugin.Snapshot.UseNameServer);
			PhotonReflection.Set(obj2, "FixedRegion", Plugin.Snapshot.FixedRegion ?? "");
			if (!string.IsNullOrEmpty(Plugin.Snapshot.AppIdRealtime))
			{
				PhotonReflection.Set(obj2, "AppIdRealtime", Plugin.Snapshot.AppIdRealtime);
			}
			Plugin.Log.LogInfo((object)("[LAN] restored the game's own settings: " + Plugin.Snapshot.Summary()));
			Plugin.Snapshot.Clear();
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] restore failed: " + ex.Message));
		}
	}

	private static int ToInt(object v)
	{
		try
		{
			return (v != null) ? Convert.ToInt32(v) : 0;
		}
		catch
		{
			return 0;
		}
	}
}
internal static class HarmonyPatcher
{
	internal static int PatchAll()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000b: Expected O, but got Unknown
		Harmony harmony = new Harmony("tiago.rounds.lanphoton");
		int num = 0;
		foreach (MethodBase item in ConnectMethods())
		{
			num += (Patch(harmony, item) ? 1 : 0);
		}
		num += (PatchForceGameServer(harmony) ? 1 : 0);
		num += (PatchRedirectHost(harmony) ? 1 : 0);
		num += (PatchRoomOpDump(harmony) ? 1 : 0);
		num += (PatchProtocolSetter(harmony) ? 1 : 0);
		Plugin.Log.LogInfo((object)$"[LAN] patched {num} connect entry point(s)");
		return num;
	}

	private static bool PatchForceGameServer(Harmony harmony)
	{
		//IL_0129: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Expected O, but got Unknown
		try
		{
			Type photonNetworkType = PhotonReflection.PhotonNetworkType;
			if (photonNetworkType == null)
			{
				return false;
			}
			PropertyInfo property = photonNetworkType.GetProperty("NetworkingClient", BindingFlags.Static | BindingFlags.Public);
			Type type = ((property != null) ? property.PropertyType : PhotonReflection.FindType("Photon.Realtime.LoadBalancingClient"));
			if (type == null)
			{
				Plugin.Log.LogWarning((object)"[LAN] no LoadBalancingClient type, cannot force game server");
				return false;
			}
			MethodInfo methodInfo = null;
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo2 in methods)
			{
				if (!(methodInfo2.Name != "Connect"))
				{
					ParameterInfo[] parameters = methodInfo2.GetParameters();
					if (parameters.Length == 3 && parameters[0].ParameterType == typeof(string) && parameters[1].ParameterType == typeof(string) && parameters[2].ParameterType.IsEnum)
					{
						methodInfo = methodInfo2;
						break;
					}
				}
			}
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"[LAN] no Connect(string,string,enum) to patch");
				return false;
			}
			HarmonyMethod val = new HarmonyMethod(typeof(HarmonyPatcher).GetMethod("ForceGameServer", BindingFlags.Static | BindingFlags.NonPublic));
			harmony.Patch((MethodBase)methodInfo, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)("[LAN] hooked " + Describe(methodInfo) + " to force ServerConnection.GameServer"));
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] could not force game server: " + ex.Message));
			return false;
		}
	}

	private static bool PatchRedirectHost(Harmony harmony)
	{
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		//IL_006b: Expected O, but got Unknown
		try
		{
			Type type = PhotonReflection.FindType("Photon.Realtime.LoadBalancingClient");
			if (type == null)
			{
				return false;
			}
			MethodInfo method = type.GetMethod("ReplacePortWithAlternative", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (method == null)
			{
				Plugin.Log.LogWarning((object)"[LAN] no ReplacePortWithAlternative to patch");
				return false;
			}
			harmony.Patch((MethodBase)method, (HarmonyMethod)null, new HarmonyMethod(typeof(HarmonyPatcher).GetMethod("RedirectHost", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)("[LAN] hooked " + Describe(method) + " to keep the game server on the LAN address"));
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] could not hook the redirect: " + ex.Message));
			return false;
		}
	}

	internal static string WantedProtocolName(Type enumType)
	{
		string digits = (((Plugin.Protocol != null) ? Plugin.Protocol.Value : "V18").Contains("16") ? "16" : "18");
		return Enum.GetNames(enumType).FirstOrDefault((string n) => n.Contains(digits));
	}

	private static bool PatchProtocolSetter(Harmony harmony)
	{
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Expected O, but got Unknown
		try
		{
			Type type = PhotonReflection.FindType("Photon.Realtime.LoadBalancingClient");
			PropertyInfo propertyInfo = ((type != null) ? type.GetProperty("SerializationProtocol") : null);
			MethodInfo methodInfo = ((propertyInfo != null) ? propertyInfo.GetSetMethod() : null);
			if (methodInfo == null)
			{
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(HarmonyPatcher).GetMethod("ProtocolPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)("[LAN] hooked LoadBalancingClient.SerializationProtocol setter (wanted: " + Plugin.Protocol.Value + ")"));
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] could not hook the protocol setter: " + ex.Message));
			return false;
		}
	}

	private static void ProtocolPrefix(object[] __args)
	{
		if (!Plugin.Enabled.Value || __args == null || __args.Length != 1 || __args[0] == null)
		{
			return;
		}
		try
		{
			Type type = __args[0].GetType();
			string text = WantedProtocolName(type);
			if (text != null && __args[0].ToString() != text)
			{
				__args[0] = Enum.Parse(type, text);
			}
		}
		catch
		{
		}
	}

	private static bool PatchRoomOpDump(Harmony harmony)
	{
		//IL_00bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_00cd: Expected O, but got Unknown
		try
		{
			Type type = PhotonReflection.FindType("ExitGames.Client.Photon.PhotonPeer");
			if (type == null)
			{
				return false;
			}
			MethodInfo methodInfo = null;
			MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public);
			foreach (MethodInfo methodInfo2 in methods)
			{
				if (!(methodInfo2.Name != "SendOperation"))
				{
					ParameterInfo[] parameters = methodInfo2.GetParameters();
					if (parameters.Length == 3 && parameters[0].ParameterType == typeof(byte) && typeof(IDictionary).IsAssignableFrom(parameters[1].ParameterType))
					{
						methodInfo = methodInfo2;
						break;
					}
				}
			}
			if (methodInfo == null)
			{
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(HarmonyPatcher).GetMethod("DumpRoomOp", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)("[LAN] hooked " + Describe(methodInfo) + " to log room requests"));
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] room request logging unavailable: " + ex.Message));
			return false;
		}
	}

	private static void DumpRoomOp(byte operationCode, object operationParameters)
	{
		if (operationCode != 227 && operationCode != 226)
		{
			return;
		}
		try
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("[LAN] op ").Append(operationCode).Append(" params: ");
			DumpValue(stringBuilder, operationParameters, 0);
			Plugin.Log.LogInfo((object)stringBuilder.ToString());
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] dump failed: " + ex.Message));
		}
	}

	private static void DumpValue(StringBuilder sb, object v, int depth)
	{
		if (depth > 6)
		{
			sb.Append("...");
			return;
		}
		if (v == null)
		{
			sb.Append("null");
			return;
		}
		Type type = v.GetType();
		if (v is byte[] array)
		{
			sb.Append("byte[").Append(array.Length).Append("]:");
			for (int i = 0; i < array.Length && i < 64; i++)
			{
				sb.Append(array[i].ToString("x2"));
			}
		}
		else if (v is string value)
		{
			sb.Append("str:\"").Append(value).Append('"');
		}
		else if (v is IDictionary dictionary)
		{
			sb.Append(type.Name).Append('{');
			bool flag = true;
			foreach (DictionaryEntry item in dictionary)
			{
				if (!flag)
				{
					sb.Append(", ");
				}
				flag = false;
				sb.Append((item.Key == null) ? "null" : (item.Key.GetType().Name + ":" + item.Key)).Append(" = ");
				DumpValue(sb, item.Value, depth + 1);
			}
			sb.Append('}');
		}
		else if (type.IsArray)
		{
			Array array2 = (Array)v;
			sb.Append(type.GetElementType().Name).Append("[").Append(array2.Length)
				.Append("][");
			for (int j = 0; j < array2.Length && j < 32; j++)
			{
				if (j > 0)
				{
					sb.Append(", ");
				}
				DumpValue(sb, array2.GetValue(j), depth + 1);
			}
			sb.Append(']');
		}
		else if (type.IsPrimitive || type.IsEnum)
		{
			sb.Append(type.Name).Append(':').Append(v);
		}
		else
		{
			sb.Append("CUSTOM ").Append(type.FullName).Append(':')
				.Append(v);
		}
	}

	private static void RedirectHost(ref string __result)
	{
		if (!Plugin.Enabled.Value || string.IsNullOrEmpty(__result))
		{
			return;
		}
		try
		{
			string text = __result;
			int num = text.LastIndexOf(':');
			string text2 = ((num > 0) ? text.Substring(num + 1) : "");
			string text3 = "";
			int num2 = text.IndexOf("://", StringComparison.Ordinal);
			if (num2 > 0)
			{
				text3 = text.Substring(0, num2 + 3);
			}
			if (text2.Length != 0 && !text2.Contains("/"))
			{
				__result = text3 + Plugin.Address.Value + ":" + text2;
				if (__result != text)
				{
					Plugin.Log.LogInfo((object)("[LAN] game server " + text + " -> " + __result));
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] redirect rewrite failed: " + ex.Message));
		}
	}

	private static void ForceGameServer(object[] __args)
	{
		if (!Plugin.ForceGameServer)
		{
			return;
		}
		try
		{
			if (__args != null && __args.Length == 3 && __args[2] != null && __args[2].GetType().IsEnum)
			{
				__args[2] = Enum.Parse(__args[2].GetType(), "GameServer");
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] force game server failed: " + ex.Message));
		}
	}

	private static IEnumerable<MethodBase> ConnectMethods()
	{
		List<MethodBase> list = ConnectTargets.Build(PhotonReflection.PhotonNetworkType, PhotonReflection.AppSettingsType);
		foreach (MethodBase item in list)
		{
			Plugin.Log.LogInfo((object)("[LAN] hook target: " + Describe(item)));
		}
		return list;
	}

	private static bool Patch(Harmony harmony, MethodBase target)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001c: Expected O, but got Unknown
		//IL_0032: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		try
		{
			HarmonyMethod val = new HarmonyMethod(typeof(HarmonyPatcher).GetMethod("BeforeConnect", BindingFlags.Static | BindingFlags.NonPublic));
			HarmonyMethod val2 = new HarmonyMethod(typeof(HarmonyPatcher).GetMethod("AfterConnect", BindingFlags.Static | BindingFlags.NonPublic));
			harmony.Patch(target, val, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)("[LAN] hooked " + Describe(target)));
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)$"[LAN] failed to hook {Describe(target)}: {ex.Message}");
			return false;
		}
	}

	private static string Describe(MethodBase m)
	{
		string text = string.Join(", ", (from p in m.GetParameters()
			select p.ParameterType.Name).ToArray());
		return m.DeclaringType.FullName + "." + m.Name + "(" + text + ")";
	}

	private static void BeforeConnect(object[] __args)
	{
		if (!Plugin.Redirecting)
		{
			return;
		}
		try
		{
			Settings.Apply("prefix BeforeConnect");
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("[LAN] prefix failed: " + ex));
		}
	}

	private static void AfterConnect(object[] __args)
	{
		if (!Plugin.Redirecting)
		{
			return;
		}
		try
		{
			object obj = PhotonReflection.GetStatic(PhotonReflection.PhotonNetworkType, "PhotonServerSettings");
			object obj2 = ((obj != null) ? PhotonReflection.Get(obj, "AppSettings") : null);
			if (obj2 != null)
			{
				Plugin.Log.LogInfo((object)string.Format("[LAN] after connect: Server={0} Port={1} UseNameServer={2}", PhotonReflection.Get(obj2, "Server"), PhotonReflection.Get(obj2, "Port"), PhotonReflection.Get(obj2, "UseNameServer")));
				Settings.Apply("postfix AfterConnect", verbose: false);
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogError((object)("[LAN] postfix failed: " + ex));
		}
	}
}
internal static class Recon
{
	private const int MaxTypes = 40;

	private const int MaxMethodsPerType = 40;

	internal static void Run(string[] filters)
	{
		string[] array = (from f in filters
			where !string.IsNullOrWhiteSpace(f)
			select f.Trim()).ToArray();
		Plugin.Log.LogInfo((object)("[LAN] recon: looking for " + string.Join(", ", array)));
		int num = 0;
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		foreach (Assembly assembly in assemblies)
		{
			Type[] array2;
			try
			{
				array2 = assembly.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				array2 = ex.Types.Where((Type t) => t != null).ToArray();
			}
			catch
			{
				continue;
			}
			Type[] array3 = array2;
			foreach (Type type in array3)
			{
				if (type == null)
				{
					continue;
				}
				string full = type.FullName ?? type.Name;
				if (!array.Any((string w) => full.IndexOf(w, StringComparison.OrdinalIgnoreCase) >= 0) || type.Name.StartsWith("<") || full.Contains("<>"))
				{
					continue;
				}
				if (num >= 40)
				{
					Plugin.Log.LogInfo((object)("[LAN] recon: type cap reached (" + 40 + "), stopping the dump"));
					Plugin.Log.LogInfo((object)"[LAN] recon: done");
					return;
				}
				num++;
				Plugin.Log.LogInfo((object)("[LAN] recon type: " + full));
				MethodInfo[] methods;
				try
				{
					methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				}
				catch
				{
					continue;
				}
				foreach (MethodInfo item in methods.Take(40))
				{
					try
					{
						Plugin.Log.LogInfo((object)("        " + (item.IsStatic ? "static " : "") + item.ReturnType.Name + " " + item.Name + "(" + string.Join(", ", (from p in item.GetParameters()
							select p.ParameterType.Name + " " + p.Name).ToArray()) + ")"));
					}
					catch
					{
					}
				}
			}
		}
		Plugin.Log.LogInfo((object)("[LAN] recon: " + num + " type(s) dumped"));
		Plugin.Log.LogInfo((object)"[LAN] recon: done");
	}
}
internal enum LanPhase
{
	Idle,
	Dialling,
	InRoom
}
internal enum LanWatch
{
	None,
	Restore
}
internal sealed class SettingsSnapshot
{
	internal bool Captured;

	internal string Server;

	internal int Port;

	internal bool UseNameServer;

	internal string AppIdRealtime;

	internal string FixedRegion;

	internal bool Take(string server, int port, bool useNameServer, string appIdRealtime, string fixedRegion)
	{
		if (Captured)
		{
			return false;
		}
		Server = server;
		Port = port;
		UseNameServer = useNameServer;
		AppIdRealtime = appIdRealtime;
		FixedRegion = fixedRegion;
		Captured = true;
		return true;
	}

	internal void Clear()
	{
		Captured = false;
		Server = null;
		AppIdRealtime = null;
		FixedRegion = null;
		Port = 0;
		UseNameServer = false;
	}

	internal string Summary()
	{
		if (!Captured)
		{
			return "(nothing to restore)";
		}
		return "Server=" + (string.IsNullOrEmpty(Server) ? "(empty)" : Server) + " Port=" + Port.ToString(CultureInfo.InvariantCulture) + " UseNameServer=" + UseNameServer + " AppId=" + (string.IsNullOrEmpty(AppIdRealtime) ? "(game default)" : AppIdRealtime);
	}
}
internal sealed class LanSession
{
	internal const float LeaveGraceSeconds = 8f;

	private float _outside;

	internal LanPhase Phase { get; private set; }

	internal string RoomName { get; private set; }

	internal bool RestorePending { get; private set; }

	internal int Failures { get; private set; }

	internal bool Redirecting
	{
		get
		{
			if (Phase != LanPhase.Dialling)
			{
				return Phase == LanPhase.InRoom;
			}
			return true;
		}
	}

	internal bool BeginDial(string roomName)
	{
		RoomName = roomName;
		_outside = 0f;
		if (Redirecting)
		{
			return false;
		}
		Phase = LanPhase.Dialling;
		return true;
	}

	internal void Opened(string roomName)
	{
		if (!string.IsNullOrEmpty(roomName))
		{
			RoomName = roomName;
		}
		Phase = LanPhase.InRoom;
		_outside = 0f;
		Failures = 0;
	}

	internal void Failed()
	{
		Phase = LanPhase.Idle;
		RestorePending = true;
		_outside = 0f;
		Failures++;
	}

	internal void Left()
	{
		Phase = LanPhase.Idle;
		RestorePending = true;
		RoomName = null;
		_outside = 0f;
	}

	internal void Restored()
	{
		Phase = LanPhase.Idle;
		RestorePending = false;
		_outside = 0f;
	}

	internal LanWatch Observe(float deltaSeconds, bool clientInRoom, bool clientConnecting)
	{
		if (Phase != LanPhase.InRoom)
		{
			return LanWatch.None;
		}
		if (clientInRoom || clientConnecting)
		{
			_outside = 0f;
			return LanWatch.None;
		}
		if (deltaSeconds > 0f)
		{
			_outside += deltaSeconds;
		}
		if (_outside < 8f)
		{
			return LanWatch.None;
		}
		Failures++;
		RestorePending = true;
		return LanWatch.Restore;
	}

	internal void Reset()
	{
		Phase = LanPhase.Idle;
		RoomName = null;
		RestorePending = false;
		Failures = 0;
		_outside = 0f;
	}
}
public sealed class LanDiscovery : IDisposable
{
	public const string Magic = "ROUNDS-LAN-PHOTON1";

	public const string Query = "ROUNDS-LAN-PHOTON1?";

	public const int DefaultPort = 47777;

	private readonly int _port;

	private readonly bool _beacon;

	private readonly int _photonPort;

	private readonly string _advertiseAddress;

	private readonly Action<string, int> _onFound;

	private readonly Action<string> _log;

	private UdpClient _client;

	private Thread _thread;

	private volatile bool _running;

	private long _lastAnnounceTicks;

	private string _lastLoggedAddress;

	private int _lastLoggedPort = -1;

	private long _lastQueryTicks;

	public string LastAddress { get; private set; }

	public int LastPort { get; private set; }

	public DateTime LastSeenUtc { get; private set; }

	public int BeaconsHeard { get; private set; }

	public bool IsBeacon => _beacon;

	public bool IsRunning => _running;

	public LanDiscovery(int port, bool beacon, string advertiseAddress, int photonPort, Action<string, int> onFound, Action<string> log)
	{
		_port = ((port <= 0) ? 47777 : port);
		_beacon = beacon;
		_advertiseAddress = advertiseAddress ?? "";
		_photonPort = photonPort;
		_onFound = onFound;
		_log = log ?? ((Action<string>)delegate
		{
		});
	}

	public void Start()
	{
		try
		{
			_client = new UdpClient();
			_client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, optionValue: true);
			_client.EnableBroadcast = true;
			_client.Client.Bind(new IPEndPoint(IPAddress.Any, _port));
			_running = true;
			_thread = new Thread(Loop)
			{
				IsBackground = true,
				Name = "RoundsLanDiscovery"
			};
			_thread.Start();
			_log(string.Format("[LAN] discovery started ({0}) on udp/{1}", _beacon ? "beacon" : "listener", _port));
		}
		catch (Exception ex)
		{
			_log("[LAN] discovery could not start: " + ex.Message);
		}
	}

	private void Loop()
	{
		IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
		while (_running)
		{
			try
			{
				if (_beacon)
				{
					Beacon();
				}
				else
				{
					Ask();
				}
				while (_client.Available > 0)
				{
					byte[] data = _client.Receive(ref remoteEP);
					Handle(data, remoteEP);
				}
				Thread.Sleep(100);
			}
			catch (ObjectDisposedException)
			{
				break;
			}
			catch (SocketException)
			{
				Thread.Sleep(250);
			}
			catch (Exception ex3)
			{
				_log("[LAN] discovery loop error: " + ex3.Message);
				Thread.Sleep(1000);
			}
		}
	}

	private void Beacon()
	{
		long ticks = DateTime.UtcNow.Ticks;
		if (ticks - Interlocked.Read(in _lastAnnounceTicks) < 20000000)
		{
			return;
		}
		Interlocked.Exchange(ref _lastAnnounceTicks, ticks);
		int num = 0;
		int photonPort;
		foreach (KeyValuePair<string, IPAddress> item in InterfaceBroadcasts())
		{
			string key = item.Key;
			photonPort = _photonPort;
			string s = "ROUNDS-LAN-PHOTON1|" + key + "|" + photonPort;
			byte[] bytes = Encoding.ASCII.GetBytes(s);
			try
			{
				_client.Send(bytes, bytes.Length, new IPEndPoint(item.Value, _port));
				num++;
			}
			catch
			{
			}
		}
		if (num != 0)
		{
			return;
		}
		string advertiseAddress = _advertiseAddress;
		photonPort = _photonPort;
		string s2 = "ROUNDS-LAN-PHOTON1|" + advertiseAddress + "|" + photonPort;
		byte[] bytes2 = Encoding.ASCII.GetBytes(s2);
		try
		{
			_client.Send(bytes2, bytes2.Length, new IPEndPoint(IPAddress.Broadcast, _port));
		}
		catch (Exception ex)
		{
			_log("[LAN] beacon send failed: " + ex.Message);
		}
	}

	private void Ask()
	{
		long ticks = DateTime.UtcNow.Ticks;
		long num = 10000000L * (long)((BeaconsHeard == 0) ? 3 : 15);
		if (ticks - _lastQueryTicks < num)
		{
			return;
		}
		_lastQueryTicks = ticks;
		byte[] bytes = Encoding.ASCII.GetBytes("ROUNDS-LAN-PHOTON1?");
		int num2 = 0;
		foreach (KeyValuePair<string, IPAddress> item in InterfaceBroadcasts())
		{
			try
			{
				_client.Send(bytes, bytes.Length, new IPEndPoint(item.Value, _port));
				num2++;
			}
			catch
			{
			}
		}
		if (num2 != 0)
		{
			return;
		}
		try
		{
			_client.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Broadcast, _port));
		}
		catch
		{
		}
	}

	private string AddressFacing(IPAddress asker)
	{
		try
		{
			byte[] addressBytes = asker.GetAddressBytes();
			NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
			foreach (NetworkInterface networkInterface in allNetworkInterfaces)
			{
				if (networkInterface.OperationalStatus != OperationalStatus.Up)
				{
					continue;
				}
				foreach (UnicastIPAddressInformation unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
				{
					if (unicastAddress.Address.AddressFamily != AddressFamily.InterNetwork || unicastAddress.IPv4Mask == null)
					{
						continue;
					}
					byte[] addressBytes2 = unicastAddress.Address.GetAddressBytes();
					byte[] addressBytes3 = unicastAddress.IPv4Mask.GetAddressBytes();
					if (addressBytes.Length != 4 || addressBytes3.Length != 4)
					{
						continue;
					}
					bool flag = true;
					for (int j = 0; j < 4; j++)
					{
						if ((addressBytes2[j] & addressBytes3[j]) != (addressBytes[j] & addressBytes3[j]))
						{
							flag = false;
							break;
						}
					}
					if (flag)
					{
						return unicastAddress.Address.ToString();
					}
				}
			}
		}
		catch
		{
		}
		return _advertiseAddress;
	}

	private static List<KeyValuePair<string, IPAddress>> InterfaceBroadcasts()
	{
		List<KeyValuePair<string, IPAddress>> list = new List<KeyValuePair<string, IPAddress>>();
		try
		{
			NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
			foreach (NetworkInterface networkInterface in allNetworkInterfaces)
			{
				if (networkInterface.OperationalStatus != OperationalStatus.Up || networkInterface.NetworkInterfaceType == NetworkInterfaceType.Loopback)
				{
					continue;
				}
				foreach (UnicastIPAddressInformation unicastAddress in networkInterface.GetIPProperties().UnicastAddresses)
				{
					if (unicastAddress.Address.AddressFamily != AddressFamily.InterNetwork || unicastAddress.IPv4Mask == null)
					{
						continue;
					}
					string text = unicastAddress.Address.ToString();
					if (text.StartsWith("169.254."))
					{
						continue;
					}
					byte[] addressBytes = unicastAddress.Address.GetAddressBytes();
					byte[] addressBytes2 = unicastAddress.IPv4Mask.GetAddressBytes();
					if (addressBytes2.Length == 4)
					{
						byte[] array = new byte[4];
						for (int j = 0; j < 4; j++)
						{
							array[j] = (byte)(addressBytes[j] | (byte)(~addressBytes2[j]));
						}
						list.Add(new KeyValuePair<string, IPAddress>(text, new IPAddress(array)));
					}
				}
			}
		}
		catch
		{
		}
		return list;
	}

	private void Handle(byte[] data, IPEndPoint from)
	{
		string text;
		try
		{
			text = Encoding.ASCII.GetString(data);
		}
		catch
		{
			return;
		}
		if (!text.StartsWith("ROUNDS-LAN-PHOTON1", StringComparison.Ordinal))
		{
			return;
		}
		if (text == "ROUNDS-LAN-PHOTON1?")
		{
			if (_beacon && from != null)
			{
				string text2 = AddressFacing(from.Address);
				Encoding aSCII = Encoding.ASCII;
				int photonPort = _photonPort;
				byte[] bytes = aSCII.GetBytes("ROUNDS-LAN-PHOTON1|" + text2 + "|" + photonPort);
				try
				{
					_client.Send(bytes, bytes.Length, from);
				}
				catch (Exception ex)
				{
					_log("[LAN] could not answer " + from?.ToString() + ": " + ex.Message);
				}
			}
		}
		else
		{
			if (_beacon)
			{
				return;
			}
			string[] array = text.Split(new char[1] { '|' });
			if (array[0] != "ROUNDS-LAN-PHOTON1")
			{
				return;
			}
			int result = _photonPort;
			string text3 = "";
			if (array.Length >= 2)
			{
				text3 = array[1].Trim();
			}
			if (array.Length >= 3)
			{
				int.TryParse(array[2].Trim(), out result);
			}
			string text4 = ((from != null && from.Address != null && !from.Address.Equals(IPAddress.Any) && !from.Address.Equals(IPAddress.None)) ? from.Address.ToString() : text3);
			if (string.IsNullOrEmpty(text4) || text4 == "127.0.0.1")
			{
				text4 = text3;
			}
			if (!string.IsNullOrEmpty(text4))
			{
				if (text4 != _lastLoggedAddress || result != _lastLoggedPort)
				{
					_lastLoggedAddress = text4;
					_lastLoggedPort = result;
					_log(string.Format("[LAN] discovered Photon server at {0}:{1} (advertised {2})", text4, result, string.IsNullOrEmpty(text3) ? "self" : text3));
				}
				LastAddress = text4;
				LastPort = result;
				LastSeenUtc = DateTime.UtcNow;
				BeaconsHeard++;
				if (_onFound != null)
				{
					_onFound(text4, result);
				}
			}
		}
	}

	public void Stop()
	{
		_running = false;
		try
		{
			if (_thread != null)
			{
				_thread.Join(1500);
			}
		}
		catch
		{
		}
		try
		{
			if (_client != null)
			{
				_client.Close();
			}
		}
		catch
		{
		}
	}

	public void Dispose()
	{
		Stop();
	}
}
internal static class Overlay
{
	private static GUIStyle _title;

	private static GUIStyle _label;

	private static GUIStyle _small;

	private static bool _stylesReady;

	private static Font _gameFont;

	private static bool _fontSearched;

	private static float _lastFontTry;

	internal static Font GameFont()
	{
		bool num = (Object)(object)_gameFont != (Object)null;
		bool flag = Time.realtimeSinceStartup - _lastFontTry > 5f;
		if (num || (_fontSearched && !flag))
		{
			return _gameFont;
		}
		_fontSearched = true;
		_lastFontTry = Time.realtimeSinceStartup;
		try
		{
			Font val = null;
			Font[] array = Resources.FindObjectsOfTypeAll<Font>();
			foreach (Font val2 in array)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				string text = ((Object)val2).name ?? "";
				if (text.Length != 0)
				{
					if (text.IndexOf("Arial", StringComparison.OrdinalIgnoreCase) < 0 && text.IndexOf("LegacyRuntime", StringComparison.OrdinalIgnoreCase) < 0)
					{
						_gameFont = val2;
						Plugin.Log.LogInfo((object)("[LAN] panel font: using the game's font '" + text + "'"));
						return _gameFont;
					}
					if ((Object)(object)val == (Object)null)
					{
						val = val2;
					}
				}
			}
			if ((Object)(object)_gameFont == (Object)null)
			{
				_gameFont = val;
			}
			if ((Object)(object)_gameFont == (Object)null)
			{
				Plugin.Log.LogInfo((object)"[LAN] panel font: nothing suitable loaded yet, will look again");
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogInfo((object)("[LAN] panel font lookup failed: " + ex.Message));
		}
		return _gameFont;
	}

	internal static void ReportFontSystem()
	{
		try
		{
			string[] array = new string[4] { "TMPro.TMP_FontAsset, Unity.TextMeshPro", "TMPro.TMP_FontAsset, TextMeshPro", "TMPro.TextMeshProUGUI, Unity.TextMeshPro", "TMPro.TextMeshProUGUI, TextMeshPro" };
			foreach (string text in array)
			{
				Type type = Type.GetType(text);
				if (type == null)
				{
					continue;
				}
				Object[] array2 = Resources.FindObjectsOfTypeAll(type);
				Plugin.Log.LogInfo((object)("[LAN] font system: " + text.Split(new char[1] { ',' })[0] + " is present, " + ((array2 != null) ? array2.Length : 0) + " loaded object(s)"));
				if (array2 == null)
				{
					return;
				}
				int num = 0;
				Object[] array3 = array2;
				foreach (Object val in array3)
				{
					if (!(val == (Object)null) && num < 3)
					{
						Plugin.Log.LogInfo((object)("[LAN]   font asset: " + val.name));
						num++;
					}
				}
				return;
			}
			Plugin.Log.LogInfo((object)"[LAN] font system: no TextMeshPro types loaded, the game is on Unity UI / IMGUI");
		}
		catch (Exception ex)
		{
			Plugin.Log.LogInfo((object)("[LAN] font system probe failed: " + ex.Message));
		}
	}

	internal static void EnsureStyles()
	{
		//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_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Expected O, but got Unknown
		//IL_003b: 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)
		//IL_004d: Expected O, but got Unknown
		//IL_0057: 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)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Expected O, but got Unknown
		if (!_stylesReady)
		{
			_stylesReady = true;
			_title = new GUIStyle(GUI.skin.label)
			{
				fontSize = 15,
				fontStyle = (FontStyle)1
			};
			_label = new GUIStyle(GUI.skin.label)
			{
				fontSize = 12
			};
			_small = new GUIStyle(GUI.skin.label)
			{
				fontSize = 10,
				wordWrap = true
			};
			Font val = GameFont();
			if ((Object)(object)val != (Object)null)
			{
				_title.font = val;
				_label.font = val;
				_small.font = val;
			}
		}
	}

	internal static void Draw(Plugin plugin)
	{
		//IL_007e: Unknown result type (might be due to invalid IL or missing references)
		EnsureStyles();
		Font val = GameFont();
		if ((Object)(object)val != (Object)null && (Object)(object)_title.font != (Object)(object)val)
		{
			_title.font = val;
			_label.font = val;
			_small.font = val;
		}
		float num = Mathf.Clamp(Plugin.UiWidth.Value, 320f, 900f);
		GUILayout.BeginArea(new Rect(20f, 20f, num, 380f), GUI.skin.box);
		GUILayout.Label("ROUNDS LAN Photon  0.8.0", _title, Array.Empty<GUILayoutOption>());
		GUILayout.Label("Toggle this panel with " + Plugin.UiToggleKey.Value, _small, Array.Empty<GUILayoutOption>());
		GUILayout.Space(4f);
		string text = (Plugin.DiscoveryMode.Value ?? "auto").Trim().ToLowerInvariant();
		GUILayout.Label("mode: " + text + "    server: " + Plugin.Address.Value + ":" + Plugin.Port.Value, _label, Array.Empty<GUILayoutOption>());
		LanDiscovery discovery = plugin.Discovery;
		if (text == "auto")
		{
			if (discovery != null && discovery.BeaconsHeard > 0)
			{
				double totalSeconds = (DateTime.UtcNow - discovery.LastSeenUtc).TotalSeconds;
				GUILayout.Label($"host found: {discovery.LastAddress}:{discovery.LastPort}  ({totalSeconds:0}s ago, {discovery.BeaconsHeard} announces)", _label, Array.Empty<GUILayoutOption>());
			}
			else
			{
				GUILayout.Label("listening for a host on udp/" + Plugin.DiscoveryPort.Value + " ...", _label, Array.Empty<GUILayoutOption>());
			}
		}
		else if (text == "host")
		{
			GUILayout.Label("this machine advertises itself at " + plugin.AdvertisedAddress() + ":" + Plugin.Port.Value, _label, Array.Empty<GUILayoutOption>());
			GUILayout.Label("tell the others nothing: their games find it by themselves.", _small, Array.Empty<GUILayoutOption>());
		}
		GUILayout.Space(4f);
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Apply now", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }))
		{
			Settings.Apply("ui");
			plugin.LogLine("settings applied from the panel");
		}
		if (GUILayout.Button("Discover again", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(130f) }))
		{
			plugin.RestartDiscovery();
		}
		GUILayout.EndHorizontal();
		GUILayout.Label("server: " + Plugin.Address.Value + ":" + Plugin.Port.Value + "   (discovery: " + Plugin.DiscoveryMode.Value + ")", _small, Array.Empty<GUILayoutOption>());
		GUILayout.Space(6f);
		GUILayout.Label("LAN room (goes straight to the server, no Steam lobby)", _label, Array.Empty<GUILayoutOption>());
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		Plugin.LanRoomName = GUILayout.TextField(Plugin.LanRoomName ?? "rounds-lan", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(190f) });
		if (GUILayout.Button("Host LAN", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }) && !Plugin.LanBusy)
		{
			Plugin.LanBusy = true;
			Plugin.LanStatus = "connecting ...";
			LanRooms.Host(Plugin.LanRoomName, delegate(bool? ok, string msg)
			{
				Plugin.LanBusy = !ok.HasValue;
				Plugin.LanStatus = ((!ok.HasValue) ? msg : ((ok.Value ? "OK: " : "FAILED: ") + msg));
				plugin.LogLine("host lan -> " + Plugin.LanStatus);
			});
		}
		if (GUILayout.Button("Join LAN", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) }) && !Plugin.LanBusy)
		{
			Plugin.LanBusy = true;
			Plugin.LanStatus = "connecting ...";
			LanRooms.Join(Plugin.LanRoomName, delegate(bool? ok, string msg)
			{
				Plugin.LanBusy = !ok.HasValue;
				Plugin.LanStatus = ((!ok.HasValue) ? msg : ((ok.Value ? "OK: " : "FAILED: ") + msg));
				plugin.LogLine("join lan -> " + Plugin.LanStatus);
			});
		}
		if (GUILayout.Button("Leave", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }) && !Plugin.LanBusy)
		{
			plugin.LeaveLan();
		}
		GUILayout.EndHorizontal();
		if (!string.IsNullOrEmpty(Plugin.LanStatus))
		{
			GUILayout.Label(Plugin.LanStatus, _small, Array.Empty<GUILayoutOption>());
		}
		GUILayout.Label("session: " + Plugin.Session.Phase.ToString() + (string.IsNullOrEmpty(Plugin.Session.RoomName) ? "" : (" '" + Plugin.Session.RoomName + "'")) + "   (Leave ends it and puts the game's own network settings back)", _small, Array.Empty<GUILayoutOption>());
		GUILayout.Label("Everyone types the same room name. The host clicks Host LAN, the others Join LAN.", _small, Array.Empty<GUILayoutOption>());
		GUILayout.Space(2f);
		GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
		if (GUILayout.Button("Hide (" + Plugin.UiToggleKey.Value + ")", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }))
		{
			plugin.SetPanelVisible(visible: false);
		}
		GUILayout.Label("or click the LAN button in the corner to bring it back", _small, Array.Empty<GUILayoutOption>());
		GUILayout.EndHorizontal();
		GUILayout.Space(2f);
		GUILayout.Label("This machine's addresses (give one to a friend only in manual mode):", _small, Array.Empty<GUILayoutOption>());
		foreach (string item in plugin.LocalAddresses())
		{
			GUILayout.Label("   " + item, _small, Array.Empty<GUILayoutOption>());
		}
		GUILayout.Space(2f);
		GUILayout.Label("Config: BepInEx/config/tiago.rounds.lanphoton.cfg", _small, Array.Empty<GUILayoutOption>());
		GUILayout.EndArea();
	}
}
internal sealed class TargetSpec
{
	internal readonly string Name;

	internal readonly Type[] Args;

	internal TargetSpec(string name, params Type[] args)
	{
		Name = name;
		Args = args ?? Type.EmptyTypes;
	}

	public override string ToString()
	{
		return Name + "(" + string.Join(", ", Array.ConvertAll(Args, (Type a) => a.Name)) + ")";
	}
}
internal static class ConnectTargets
{
	private static readonly BindingFlags Flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

	internal static List<TargetSpec> Wanted(Type appSettingsType)
	{
		List<TargetSpec> list = new List<TargetSpec>();
		list.Add(new TargetSpec("ConnectUsingSettings"));
		list.Add(new TargetSpec("ConnectToMaster", typeof(string), typeof(int), typeof(string)));
		list.Add(new TargetSpec("ConnectToRegion", typeof(string)));
		list.Add(new TargetSpec("ConnectToBestCloudServer"));
		list.Add(new TargetSpec("Reconnect"));
		list.Add(new TargetSpec("ReconnectAndRejoin"));
		List<TargetSpec> list2 = list;
		if (appSettingsType != null)
		{
			list2.Add(new TargetSpec("ConnectUsingSettings", appSettingsType, typeof(bool)));
		}
		return list2;
	}

	internal static List<MethodBase> Build(Type photonNetwork, Type appSettingsType = null)
	{
		List<MethodBase> list = new List<MethodBase>();
		if (photonNetwork == null)
		{
			return list;
		}
		foreach (TargetSpec item in Wanted(appSettingsType))
		{
			try
			{
				MethodInfo method = photonNetwork.GetMethod(item.Name, Flags, null, item.Args, null);
				if (method != null && !list.Contains(method))
				{
					list.Add(method);
				}
			}
			catch (Exception)
			{
			}
		}
		try
		{
			MethodInfo[] methods = photonNetwork.GetMethods(Flags);
			foreach (MethodInfo methodInfo in methods)
			{
				if (!methodInfo.IsAbstract && !methodInfo.ContainsGenericParameters && (methodInfo.Name.StartsWith("Connect") || methodInfo.Name == "Reconnect") && methodInfo.GetParameters().Length <= 4 && !list.Contains(methodInfo))
				{
					list.Add(methodInfo);
				}
			}
		}
		catch (Exception)
		{
		}
		return list;
	}
}
internal static class MenuProbe
{
	private const int MaxItemsPerPage = 24;

	internal static void Run()
	{
		try
		{
			Type type = PhotonReflection.FindType("ListMenu");
			Type type2 = PhotonReflection.FindType("ListMenuPage");
			Type type3 = PhotonReflection.FindType("ListMenuButton");
			Plugin.Log.LogInfo((object)("[LAN] menu probe: ListMenu=" + Describe(type) + " ListMenuPage=" + Describe(type2) + " ListMenuButton=" + Describe(type3)));
			if (type2 == null && type3 == null)
			{
				Plugin.Log.LogInfo((object)"[LAN] menu probe: no menu types found, nothing to report");
				return;
			}
			object obj = null;
			if (type != null)
			{
				obj = PhotonReflection.GetStatic(type, "instance");
				Plugin.Log.LogInfo((object)("[LAN] menu probe: ListMenu.instance = " + ((obj == null) ? "null" : Name(obj))));
			}
			List<object> list = FindAll(type2);
			List<object> list2 = FindAll(type3);
			Plugin.Log.LogInfo((object)("[LAN] menu probe: pages in scene = " + list.Count + ", buttons in scene = " + list2.Count));
			if (obj != null)
			{
				string[] array = new string[4] { "selectedPage", "selectedButton", "menuCanvas", "bar" };
				foreach (string text in array)
				{
					object obj2 = PhotonReflection.Get(obj, text);
					Plugin.Log.LogInfo((object)("[LAN]   ListMenu." + text + " = " + ((obj2 == null) ? "null" : Name(obj2))));
				}
			}
			int num = 0;
			foreach (object item in list2)
			{
				if (item != null && num < 120)
				{
					num++;
					Component c = (Component)((item is Component) ? item : null);
					Plugin.Log.LogInfo((object)("[LAN]   button '" + Name(item) + "'  path=" + Path(c) + "  label='" + Label(item) + "'" + Wiring(c)));
				}
			}
			foreach (object item2 in list)
			{
				if (item2 == null)
				{
					continue;
				}
				Component val = (Component)((item2 is Component) ? item2 : null);
				Plugin.Log.LogInfo((object)("[LAN]   page '" + Name(item2) + "'  path=" + Path(val)));
				if ((Object)(object)val == (Object)null || type3 == null)
				{
					continue;
				}
				List<object> list3 = new List<object>();
				try
				{
					Object[] array2 = Resources.FindObjectsOfTypeAll(type3);
					foreach (Object obj3 in array2)
					{
						Component val2 = (Component)(object)((obj3 is Component) ? obj3 : null);
						if (!((Object)(object)val2 == (Object)null) && val2.transform.IsChildOf(val.transform))
						{
							list3.Add(val2);
						}
					}
				}
				catch
				{
				}
				foreach (object item3 in list3.Take(24))
				{
					Plugin.Log.LogInfo((object)("[LAN]       child button '" + Name(item3) + "' label='" + Label(item3) + "'"));
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] menu probe failed: " + ex));
		}
	}

	private static List<object> FindAll(Type t)
	{
		List<object> list = new List<object>();
		if (t == null)
		{
			return list;
		}
		try
		{
			Object[] array = Resources.FindObjectsOfTypeAll(t);
			foreach (Object val in array)
			{
				if (val != (Object)null)
				{
					list.Add(val);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogInfo((object)("[LAN] menu probe: FindObjectsOfTypeAll(" + t.Name + ") failed: " + ex.Message));
		}
		return list;
	}

	private static string Describe(Type t)
	{
		if (t == null)
		{
			return "NOT FOUND";
		}
		return t.Assembly.GetName().Name;
	}

	private static string Name(object o)
	{
		try
		{
			Object val = (Object)((o is Object) ? o : null);
			return ((val != null) ? val.name : (PhotonReflection.Get(o, "name") as string)) ?? "(unnamed)";
		}
		catch
		{
			return "(unnamed)";
		}
	}

	private static string Path(Component c)
	{
		if ((Object)(object)c == (Object)null)
		{
			return "-";
		}
		try
		{
			List<string> list = new List<string>();
			Transform val = c.transform;
			int num = 0;
			while ((Object)(object)val != (Object)null && num++ < 12)
			{
				list.Insert(0, ((Object)val).name);
				val = val.parent;
			}
			return string.Join("/", list.ToArray());
		}
		catch
		{
			return "-";
		}
	}

	private static string Label(object button)
	{
		try
		{
			object obj = PhotonReflection.Get(button, "text");
			if (obj != null)
			{
				string text = PhotonReflection.Get(obj, "text") as string;
				if (!string.IsNullOrEmpty(text))
				{
					return text.Replace("\n", " ").Trim();
				}
			}
		}
		catch
		{
		}
		return "(no text)";
	}

	private static string Wiring(Component c)
	{
		if ((Object)(object)c == (Object)null)
		{
			return "";
		}
		try
		{
			Type type = Type.GetType("UnityEngine.UI.Button, UnityEngine.UI");
			if (type == null)
			{
				return "  [no UnityEngine.UI.Button type]";
			}
			Component component = c.gameObject.GetComponent(type);
			if ((Object)(object)component == (Object)null)
			{
				return "  [no UI Button on this object]";
			}
			object? value = type.GetProperty("onClick").GetValue(component, null);
			UnityEventBase val = (UnityEventBase)((value is UnityEventBase) ? value : null);
			int num = ((val != null) ? val.GetPersistentEventCount() : (-1));
			List<string> list = new List<string>();
			if (val != null)
			{
				for (int i = 0; i < num && i < 4; i++)
				{
					list.Add(((object)val.GetPersistentTarget(i))?.ToString() + "." + val.GetPersistentMethodName(i));
				}
			}
			return "  onClick persistent=" + num + ((list.Count > 0) ? (" targets=[" + string.Join(", ", list.ToArray()) + "]") : "");
		}
		catch (Exception ex)
		{
			return "  [wiring unreadable: " + ex.Message + "]";
		}
	}
}
internal static class LanRooms
{
	internal delegate void Report(bool? ok, string message);

	private static string _lobbyLine = "";

	internal static void Host(string roomName, Report report)
	{
		Start("CreateRoom", roomName, report);
	}

	internal static void Join(string roomName, Report report)
	{
		Start("JoinRoom", roomName, report);
	}

	private static void Start(string kind, string roomName, Report report)
	{
		if ((Object)(object)Plugin.Instance == (Object)null)
		{
			report(false, "the plugin is not ready");
		}
		else
		{
			((MonoBehaviour)Plugin.Instance).StartCoroutine(CoRoom(kind, roomName, report));
		}
	}

	private static void Fail(Report report, string why)
	{
		Plugin.Log.LogWarning((object)("[LAN] " + why));
		Plugin.Session.Failed();
		report(false, why + " The game's own settings are being put back.");
		if ((Object)(object)Plugin.Instance != (Object)null)
		{
			((MonoBehaviour)Plugin.Instance).StartCoroutine(RecoverSoon());
		}
	}

	private static IEnumerator RecoverSoon()
	{
		yield return (object)new WaitForSecondsRealtime(0.5f);
		Plugin.RecoverNow("the LAN attempt failed");
	}

	private static IEnumerator CoRoom(string kind, string roomName, Report report)
	{
		string what = ((kind == "CreateRoom") ? "host" : "join");
		if (string.IsNullOrEmpty(roomName))
		{
			report(false, "the room name is empty");
			yield break;
		}
		Type pn = PhotonReflection.PhotonNetworkType;
		if (pn == null)
		{
			Fail(report, "PhotonNetwork not found");
			yield break;
		}
		Plugin.Session.BeginDial(roomName);
		if (GetBool(pn, "InRoom"))
		{
			string current = PhotonReflection.Get(PhotonReflection.GetStatic(pn, "CurrentRoom"), "Name") as string;
			bool flag = GetBool(pn, "IsMasterClient");
			if (current == roomName && (kind == "JoinRoom" || flag))
			{
				Plugin.Session.Opened(roomName);
				OpenPrivateRoom();
				DecorateLobby(roomName);
				report(true, "already in '" + roomName + "' on " + Endpoint() + (flag ? ", you are the master" : ", master is the other player"));
				yield break;
			}
			report(null, "leaving '" + current + "' first ...");
			yield return GameRestart(pn);
			if (GetBool(pn, "InRoom"))
			{
				report(false, "could not leave '" + current + "' (state " + StateName(pn) + ")");
				yield break;
			}
		}
		if (kind == "CreateRoom")
		{
			bool retarget = Plugin.Instance.BecomeHost();
			if (!LocalServer.Ensure(out var status))
			{
				Fail(report, status);
				yield break;
			}
			report(null, status);
			float up = 0f;
			while (!LocalServer.Running() && up < 8f)
			{
				up += Time.unscaledDeltaTime;
				yield return null;
			}
			if (!LocalServer.Running())
			{
				Fail(report, "the LAN server did not start (see the game log)");
				yield break;
			}
			if (retarget && GetBool(pn, "IsConnected") && !GetBool(pn, "OfflineMode"))
			{
				CallStatic(pn, "Disconnect", Type.EmptyTypes, null);
				float gone = 0f;
				while (GetBool(pn, "IsConnected") && gone < 5f)
				{
					gone += Time.unscaledDeltaTime;
					yield return null;
				}
			}
		}
		SetStatic(pn, "OfflineMode", false);
		if (!IsReady(pn))
		{
			report(null, "connecting to " + Endpoint() + " ...");
			CallStatic(pn, "ConnectUsingSettings", Type.EmptyTypes, null);
			float up = 0f;
			while (!IsReady(pn) && up < 12f)
			{
				up += Time.unscaledDeltaTime;
				yield return null;
			}
		}
		if (!IsReady(pn))
		{
			Fail(report, "no answer from " + Endpoint() + ". Is the server running on that machine, and is udp reachable?");
			yield break;
		}
		SetPhotonLog(pn);
		if (OpenPrivateRoom())
		{
			report(null, "opened the private room page");
		}
		if (!InvokeRoom(kind, pn, roomName, out var result, out var why))
		{
			Fail(report, why);
			yield break;
		}
		if (!(result is bool) || !(bool)result)
		{
			Plugin.Log.LogInfo((object)("[LAN] " + kind + " refused in state " + StateName(pn) + "; waiting for the master server and retrying once"));
			yield return WaitForMaster(pn, 8f);
			if (!InvokeRoom(kind, pn, roomName, out result, out why))
			{
				Fail(report, why);
				yield break;
			}
			if (!(result is bool) || !(bool)result)
			{
				Fail(report, kind + " was refused twice (see the game log)");
				yield break;
			}
		}
		float opened = 0f;
		string lastSeen = "";
		while (!GetBool(pn, "InRoom") && opened < 20f)
		{
			string text = ClientState(pn);
			if (text != lastSeen)
			{
				Plugin.Log.LogInfo((object)("[LAN] state " + text));
				lastSeen = text;
			}
			opened += Time.unscaledDeltaTime;
			yield return null;
		}
		if (!GetBool(pn, "InRoom"))
		{
			Fail(report, what + " was sent, but no room opened (see the game log)");
			yield break;
		}
		Plugin.Log.LogInfo((object)("[LAN] private room page open=" + PrivateRoomOpen() + " players=" + PhotonReflection.Get(PhotonReflection.GetStatic(pn, "CurrentRoom"), "PlayerCount")));
		bool flag2 = GetBool(pn, "IsMasterClient");
		string text2 = null;
		try
		{
			text2 = PhotonReflection.Get(PhotonReflection.GetStatic(pn, "CurrentRoom"), "Name") as string;
		}
		catch
		{
		}
		bool flag3 = !string.IsNullOrEmpty(text2) && text2 != roomName;
		if (flag3)
		{
			Plugin.Log.LogWarning((object)("[LAN] the server put this player in room '" + text2 + "' although '" + roomName + "' was asked for. With one room on the host this goes unnoticed; with two it joins the wrong one."));
		}
		Plugin.Session.Opened(flag3 ? text2 : roomName);
		DecorateLobby(flag3 ? text2 : roomName);
		report(true, ((kind == "CreateRoom") ? "room '" : "joined '") + (flag3 ? text2 : roomName) + "' on " + Endpoint() + (flag2 ? ", you are the master" : ", master is the other player") + (flag3 ? (" (you asked for '" + roomName + "')") : ""));
	}

	private static Type PrivateRoomType()
	{
		return PhotonReflection.FindType("RWF.PrivateRoomHandler");
	}

	private static object PrivateRoomInstance()
	{
		Type type = PrivateRoomType();
		if (!(type == null))
		{
			return PhotonReflection.GetStatic(type, "instance");
		}
		return null;
	}

	internal static void DecorateLobby(string roomName)
	{
		try
		{
			object obj = PrivateRoomInstance();
			if (obj == null)
			{
				return;
			}
			object obj2 = PhotonReflection.Get(obj, "inviteText");
			Component val = (Component)((obj2 is Component) ? obj2 : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			string text = ((Plugin.Address.Value == "127.0.0.1") ? LocalServer.BestLanAddress() : Plugin.Address.Value);
			_lobbyLine = "room " + roomName + " on " + text;
			SetTmp(val, "LAN ROOM: " + roomName.ToUpperInvariant());
			Type type = PhotonReflection.FindType("UnityEngine.UI.Button");
			Component val2 = null;
			Transform val3 = val.transform;
			while ((Object)(object)val3 != (Object)null && (Object)(object)val2 == (Object)null)
			{
				val2 = ((type != null) ? ((Component)val3).GetComponent(type) : null);
				val3 = val3.parent;
			}
			if (!((Object)(object)val2 == (Object)null))
			{
				object obj3 = PhotonReflection.Get(val2, "onClick");
				if (obj3 != null)
				{
					obj3.GetType().GetMethod("RemoveAllListeners").Invoke(obj3, null);
					MethodInfo? method = obj3.GetType().GetMethod("AddListener");
					Delegate obj4 = Delegate.CreateDelegate(method.GetParameters()[0].ParameterType, typeof(LanRooms).GetMethod("CopyLobbyLine", BindingFlags.Static | BindingFlags.NonPublic));
					method.Invoke(obj3, new object[1] { obj4 });
					Plugin.Log.LogInfo((object)("[LAN] lobby: INVITE is now 'LAN ROOM: " + roomName + "' (click copies '" + _lobbyLine + "')"));
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] lobby label failed: " + ex.Message));
		}
	}

	private static void CopyLobbyLine()
	{
		try
		{
			GUIUtility.systemCopyBuffer = _lobbyLine;
			Plugin.Log.LogInfo((object)("[LAN] lobby: copied '" + _lobbyLine + "'"));
		}
		catch
		{
		}
	}

	private static void SetTmp(object tmp, string s)
	{
		PropertyInfo property = tmp.GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public);
		if (property != null)
		{
			property.SetValue(tmp, s, null);
		}
	}

	internal static bool OpenPrivateRoom()
	{
		try
		{
			Type type = PrivateRoomType();
			if (type == null)
			{
				Plugin.Log.LogInfo((object)"[LAN] Rounds With Friends is not installed: no private room page to open");
				return false;
			}
			object obj = PhotonReflection.GetStatic(type, "instance");
			if (obj == null)
			{
				Plugin.Log.LogWarning((object)"[LAN] RWF is loaded but its private room page is not in the menu yet");
				return false;
			}
			MethodInfo method = type.GetMethod("Open", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
			if (method == null)
			{
				Plugin.Log.LogWarning((object)"[LAN] RWF PrivateRoomHandler.Open() not found");
				return false;
			}
			method.Invoke(obj, null);
			Plugin.Log.LogInfo((object)"[LAN] opened RWF's private room page");
			return true;
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] could not open the private room page: " + ex.Message));
			return false;
		}
	}

	internal static string PrivateRoomOpen()
	{
		try
		{
			object obj = PrivateRoomInstance();
			if (obj == null)
			{
				return "no-page";
			}
			return (PhotonReflection.Get(obj, "IsOpen") is bool flag) ? flag.ToString() : "?";
		}
		catch
		{
			return "?";
		}
	}

	private static void SetPhotonLog(Type pn)
	{
		try
		{
			object obj = PhotonReflection.GetStatic(pn, "NetworkingClient");
			if (obj != null)
			{
				object obj2 = PhotonReflection.Get(obj, "LoadBalancingPeer");
				PropertyInfo property = ((obj2 != null) ? obj2.GetType() : obj.GetType()).GetProperty("DebugOut", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (property == null || !property.CanWrite)
				{
					Plugin.Log.LogWarning((object)"[LAN] no DebugOut to set");
					return;
				}
				property.SetValue(obj2 ?? obj, Enum.Parse(property.PropertyType, "ALL"), null);
				Plugin.Log.LogInfo((object)"[LAN] photon debug: ALL");
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] photon log level failed: " + ex.Message));
		}
	}

	private static string ClientState(Type pn)
	{
		try
		{
			object obj = PhotonReflection.GetStatic(pn, "NetworkingClient");
			string text = "Ready=" + GetBool(pn, "InRoom");
			if (obj != null)
			{
				text = text + " State=" + PhotonReflection.Get(obj, "State")?.ToString() + " Server=" + PhotonReflection.Get(obj, "Server")?.ToString() + " Addr=" + PhotonReflection.Get(obj, "ServerAddress")?.ToString() + " Game=" + PhotonReflection.Get(obj, "GameServerAddress")?.ToString() + " Peer=" + PhotonReflection.Get(PhotonReflection.Get(obj, "LoadBalancingPeer"), "PeerState");
			}
			return text + " Conn=" + GetBool(pn, "IsConnected") + " Ready=" + GetBool(pn, "IsConnectedAndReady");
		}
		catch (Exception ex)
		{
			return "trace failed: " + ex.Message;
		}
	}

	internal static IEnumerator GameRestart(Type pn)
	{
		object obj = null;
		MethodInfo methodInfo = null;
		Type type = PhotonReflection.FindType("NetworkConnectionHandler");
		if (type != null)
		{
			obj = PhotonReflection.GetStatic(type, "instance");
			methodInfo = type.GetMethod("NetworkRestart", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
		}
		if (obj == null || methodInfo == null)
		{
			Plugin.Log.LogWarning((object)"[LAN] NetworkConnectionHandler.NetworkRestart not found; leaving with LeaveRoom");
			CallStatic(pn, "LeaveRoom", new Type[1] { typeof(bool) }, new object[1] { false });
			yield return WaitForMaster(pn, 12f);
			yield break;
		}
		float before = Time.timeSinceLevelLoad;
		methodInfo.Invoke(obj, null);
		Plugin.Log.LogInfo((object)"[LAN] asked the game to leave the room (NetworkRestart)");
		float t0 = 0f;
		while (t0 < 10f && !LeftEverything(pn))
		{
			t0 += Time.unscaledDeltaTime;
			yield return null;
		}
		float t1 = 0f;
		while (Time.timeSinceLevelLoad >= before && t1 < 10f)
		{
			t1 += Time.unscaledDeltaTime;
			yield return null;
		}
		yield return (object)new WaitForSecondsRealtime(1.5f);
		Plugin.Log.LogInfo((object)("[LAN] game restarted its network (" + (t0 + t1).ToString("0.0") + " s), state " + StateName(pn)));
	}

	private static int StateValue(Type pn)
	{
		try
		{
			object obj = PhotonReflection.GetStatic(pn, "NetworkingClient");
			object obj2 = ((obj == null) ? null : PhotonReflection.Get(obj, "State"));
			return (obj2 == null) ? (-1) : Convert.ToInt32(obj2);
		}
		catch
		{
			return -1;
		}
	}

	private static string StateName(Type pn)
	{
		object obj = PhotonReflection.GetStatic(pn, "NetworkingClient");
		object obj2 = ((obj == null) ? null : PhotonReflection.Get(obj, "State"));
		if (obj2 != null)
		{
			return obj2?.ToString() + " (" + StateValue(pn) + ")";
		}
		return "unknown";
	}

	private static bool OnMaster(Type pn)
	{
		int num = StateValue(pn);
		if (num == 15 || num == 4)
		{
			return IsReady(pn);
		}
		return false;
	}

	private static IEnumerator WaitForMaster(Type pn, float limit)
	{
		float t = 0f;
		bool redialled = false;
		while (!OnMaster(pn) && t < limit)
		{
			if (!redialled && StateValue(pn) == 14)
			{
				redialled = true;
				Plugin.Log.LogInfo((object)"[LAN] client is disconnected after the leave; connecting again");
				CallStatic(pn, "ConnectUsingSettings", Type.EmptyTypes, null);
			}
			t += Time.unscaledDeltaTime;
			yield return null;
		}
	}

	private static bool LeftEverything(Type pn)
	{
		if (GetBool(pn, "OfflineMode"))
		{
			return true;
		}
		if (!GetBool(pn, "InRoom"))
		{
			return !GetBool(pn, "IsConnected");
		}
		return false;
	}

	private static string Endpoint()
	{
		return Plugin.Address.Value + ":" + Plugin.Port.Value;
	}

	private static bool IsReady(Type pn)
	{
		object obj = PhotonReflection.GetStatic(pn, "IsConnectedAndReady");
		if (obj is bool)
		{
			return (bool)obj;
		}
		return GetBool(pn, "IsConnected");
	}

	private static bool InvokeRoom(string kind, Type pn, string roomName, out object result, out string why)
	{
		result = null;
		why = "";
		Type type = PhotonReflection.FindType("Photon.Realtime.RoomOptions");
		Type type2 = PhotonReflection.FindType("Photon.Realtime.TypedLobby");
		if (type == null || type2 == null)
		{
			why = "RoomOptions or TypedLobby not found";
			return false;
		}
		object obj = Activator.CreateInstance(type);
		TrySet(obj, "MaxPlayers", (byte)16);
		TrySet(obj, "IsVisible", false);
		TrySet(obj, "IsOpen", true);
		TrySet(obj, "CleanupCacheOnLeave", true);
		object obj2 = PhotonReflection.GetStatic(type2, "Default");
		if (obj2 == null)
		{
			obj2 = Activator.CreateInstance(type2);
		}
		MethodInfo method;
		object[] parameters;
		if (kind == "CreateRoom")
		{
			method = pn.GetMethod("CreateRoom", new Type[4]
			{
				typeof(string),
				type,
				type2,
				typeof(string[])
			});
			parameters = new object[4] { roomName, obj, obj2, null };
		}
		else
		{
			method = pn.GetMethod("JoinRoom", new Type[2]
			{
				typeof(string),
				typeof(string[])
			});
			parameters = new object[2] { roomName, null };
		}
		if (method == null)
		{
			why = kind + " signature not found";
			return false;
		}
		try
		{
			result = method.Invoke(null, parameters);
			return true;
		}
		catch (Exception ex)
		{
			Exception ex2 = ((ex is TargetInvocationException { InnerException: not null } ex3) ? ex3.InnerException : ex);
			why = kind + " threw " + ex2.GetType().Name + ": " + ex2.Message;
			return false;
		}
	}

	private static bool GetBool(Type t, string name)
	{
		object obj = PhotonReflection.GetStatic(t, name);
		bool flag = default(bool);
		int num;
		if (obj is bool)
		{
			flag = (bool)obj;
			num = 1;
		}
		else
		{
			num = 0;
		}
		return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
	}

	private static void SetStatic(Type t, string name, object value)
	{
		try
		{
			PropertyInfo property = t.GetProperty(name, BindingFlags.Static | BindingFlags.Public);
			if (property != null && property.CanWrite)
			{
				property.SetValue(null, value, null);
			}
		}
		catch
		{
		}
	}

	private static object CallStatic(Type t, string name, Type[] types, object[] args)
	{
		try
		{
			MethodInfo method = t.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, types, null);
			if (method == null)
			{
				return null;
			}
			return method.Invoke(null, args);
		}
		catch
		{
			return null;
		}
	}

	private static void TrySet(object target, string property, object value)
	{
		try
		{
			PropertyInfo property2 = target.GetType().GetProperty(property);
			if (property2 != null && property2.CanWrite)
			{
				property2.SetValue(target, value, null);
			}
		}
		catch
		{
		}
	}
}
internal static class LanMenuPage
{
	private const string PageName = "LAN";

	private static bool _installed;

	private static bool _built;

	private static GameObject _page;

	private static object _statusText;

	private static string _status = "not connected";

	private static Type _menuHandler;

	private static Type _unityAction;

	private static object _hostText;

	internal static bool Installed
	{
		get
		{
			if (_installed)
			{
				return (Object)(object)_page != (Object)null;
			}
			return false;
		}
	}

	internal static void Install(Plugin host)
	{
		try
		{
			((MonoBehaviour)host).StartCoroutine(InstallRoutine(host));
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] native menu: could not start: " + ex.Message));
		}
	}

	private static IEnumerator InstallRoutine(Plugin host)
	{
		int failures = 0;
		bool gaveUp = false;
		while (true)
		{
			if (!Installed)
			{
				if (_installed)
				{
					Plugin.Log.LogInfo((object)"[LAN] native menu: the menu was rebuilt, adding LAN again");
				}
				_installed = false;
				_built = false;
				_page = null;
				_statusText = null;
				_hostText = null;
				bool flag = false;
				try
				{
					flag = TryInstall();
				}
				catch (Exception ex)
				{
					Exception ex2 = ((ex is TargetInvocationException && ex.InnerException != null) ? ex.InnerException : ex);
					if (failures < 3)
					{
						Plugin.Log.LogInfo((object)("[LAN] native menu: not ready yet (" + ex2.GetType().Name + ")"));
					}
				}
				if (!flag)
				{
					int num = failures + 1;
					failures = num;
					if (num == 240 && !gaveUp)
					{
						gaveUp = true;
						Plugin.Log.LogInfo((object)"[LAN] native menu: main menu not found, the F8 panel is still available");
						host.NativeMenuUnavailable();
					}
				}
				if (flag)
				{
					failures = 0;
				}
			}
			else if (_built)
			{
				RefreshHostLine();
			}
			yield return (object)new WaitForSecondsRealtime(_installed ? 1f : 0.5f);
		}
	}

	private static void RefreshHostLine()
	{
		LanDiscovery lanDiscovery = (((Object)(object)Plugin.Instance != (Object)null) ? Plugin.Instance.Discovery : null);
		SetText(s: (lanDiscovery != null && lanDiscovery.IsBeacon) ? ("YOU ARE HOSTING. FRIENDS FIND " + LocalServer.BestLanAddress() + " BY THEMSELVES") : ((lanDiscovery == null || lanDiscovery.BeaconsHeard <= 0 || !((DateTime.UtcNow - lanDiscovery.LastSeenUtc).TotalSeconds < 20.0)) ? "NO HOST FOUND YET. ONE PC PRESSES HOST, THE OTHERS JOIN" : ("HOST FOUND ON YOUR NETWORK: " + lanDiscovery.LastAddress)), tmp: _hostText);
	}

	private static bool TryInstall()
	{
		//IL_0186: Unknown result type (might be due to invalid IL or missing references)
		//IL_0190: Expected O, but got Unknown
		_menuHandler = PhotonReflection.FindType("UnboundLib.Utils.UI.MenuHandler");
		if (_menuHandler == null)
		{
			return false;
		}
		GameObject val = FindMainPage();
		if ((Object)(object)val == (Object)null)
		{
			return false;
		}
		MethodInfo methodInfo = null;
		MethodInfo[] methods = _menuHandler.GetMethods(BindingFlags.Static | BindingFlags.Public);
		foreach (MethodInfo methodInfo2 in methods)
		{
			if (!(methodInfo2.Name != "CreateMenu"))
			{
				ParameterInfo[] parameters = methodInfo2.GetParameters();
				if (parameters.Length == 10 && parameters[3].ParameterType.IsByRef)
				{
					methodInfo = methodInfo2;
					break;
				}
			}
		}
		if (methodInfo == null)
		{
			Plugin.Log.LogWarning((object)"[LAN] native menu: CreateMenu signature not found");
			return false;
		}
		_unityAction = methodInfo.GetParameters()[1].ParameterType;
		if (!typeof(Delegate).IsAssignableFrom(_unityAction.BaseType) && !typeof(MulticastDelegate).IsAssignableFrom(_unityAction))
		{
			Plugin.Log.LogWarning((object)("[LAN] native menu: unexpected action type " + _unityAction));
			return false;
		}
		Delegate obj = Delegate.CreateDelegate(_unityAction, typeof(LanMenuPage).GetMethod("OnOpen", BindingFlags.Static | BindingFlags.NonPublic));
		object[] array = new object[10] { "LAN", obj, val, null, 50, true, true, null, true, 2 };
		_page = (GameObject)methodInfo.Invoke(null, array);
		if ((Object)(object)_page == (Object)null)
		{
			return false;
		}
		_installed = true;
		object obj2 = array[3];
		GameObject val2 = (GameObject)((obj2 is GameObject) ? obj2 : null);
		string text = "(button not returned)";
		if ((Object)(object)val2 != (Object)null && (Object)(object)val2.transform.parent != (Object)null)
		{
			Transform parent = val2.transform.parent;
			List<string> list = new List<string>();
			for (int j = 0; j < parent.childCount; j++)
			{
				if (((Component)parent.GetChild(j)).gameObject.activeSelf)
				{
					list.Add(((Object)parent.GetChild(j)).name);
				}
			}
			text = PathOf(parent) + " [" + string.Join(", ", list.ToArray()) + "]";
		}
		Plugin.Log.LogInfo((object)("[LAN] native menu: added the 'LAN' page under " + PathOf(val.transform) + ", button order " + text));
		return true;
	}

	private static GameObject FindMainPage()
	{
		Type type = PhotonReflection.FindType("MainMenuHandler");
		if (type != null)
		{
			object obj = PhotonReflection.GetStatic(type, "instance");
			Component val = (Component)((obj is Component) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				Transform val2 = val.transform.Find("Canvas/ListSelector/Main");
				if ((Object)(object)val2 != (Object)null)
				{
					return ((Component)val2).gameObject;
				}
			}
		}
		Type type2 = PhotonReflection.FindType("ListMenuPage");
		if (type2 == null)
		{
			return null;
		}
		try
		{
			Object[] array = Object.FindObjectsOfType(type2);
			foreach (Object obj2 in array)
			{
				Component val3 = (Component)(object)((obj2 is Component) ? obj2 : null);
				if (!((Object)(object)val3 == (Object)null) && !(((Object)val3.gameObject).name != "Main") && PathOf(val3.transform).Contains("UI_MainMenu/Canvas/ListSelector/Main"))
				{
					return val3.gameObject;
				}
			}
		}
		catch
		{
		}
		return null;
	}

	private static string PathOf(Transform t)
	{
		string text = ((Object)t).name;
		Transform parent = t.parent;
		while ((Object)(object)parent != (Object)null)
		{
			text = ((Object)parent).name + "/" + text;
			parent = parent.parent;
		}
		return text;
	}

	private static string ButtonOrder(GameObject page)
	{
		try
		{
			Transform val = page.transform.Find("Group/Grid/Scroll View/Viewport/Content");
			if ((Object)(object)val == (Object)null)
			{
				return "(no content)";
			}
			List<string> list = new List<string>();
			for (int i = 0; i < val.childCount; i++)
			{
				Transform child = val.GetChild(i);
				if (((Component)child).gameObject.activeSelf)
				{
					list.Add(((Object)child).name);
				}
			}
			return string.Join(", ", list.ToArray());
		}
		catch (Exception ex)
		{
			return "(" + ex.Message + ")";
		}
	}

	internal static bool OpenForTest()
	{
		if (!Installed)
		{
			return false;
		}
		try
		{
			Type type = PhotonReflection.FindType("ListMenuPage");
			Type type2 = PhotonReflection.FindType("ListMenu");
			Component component = _page.GetComponent(type);
			object obj = PhotonReflection.GetStatic(type2, "instance");
			type2.GetMethod("OpenPage", BindingFlags.Instance | BindingFlags.Public).Invoke(obj, new object[1] { component });
			OnOpen();
			Plugin.Log.LogInfo((object)("[LAN] native menu: LAN page opened for the test, page order: " + PageOrder()));
			return true;
		}
		catch (Exception ex)
		{
			Exception ex2 = ex.InnerException ?? ex;
			Plugin.Log.LogWarning((object)("[LAN] native menu: test open failed: " + ex2.Message));
			return false;
		}
	}

	private static string PageOrder()
	{
		if (!((Object)(object)_page == (Object)null))
		{
			return ButtonOrder(_page);
		}
		return "(none)";
	}

	private static void OnOpen()
	{
		if (_built || (Object)(object)_page == (Object)null)
		{
			return;
		}
		_built = true;
		try
		{
			_hostText = CreateText("", 34, upper: true);
			RefreshHostLine();
			CreateInputField("ROOM NAME", 50, OnRoomNameChanged, Plugin.LanRoomName);
			CreateButton("HOST", HostClicked);
			CreateButton("JOIN", JoinClicked);
			CreateButton("LEAVE", LeaveClicked);
			_statusText = CreateText((_status == "not connected") ? "SAME ROOM NAME ON EVERY PC" : _status, 30, upper: true);
			Plugin.Log.LogInfo((object)"[LAN] native menu: LAN page built");
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("[LAN] native menu: building the page failed: " + ex.Message));
		}
	}

	private static void HostClicked()
	{
		Connect(host: true);
	}

	private static void JoinClicked()
	{
		Connect(host: false);
	}

	private static void LeaveClicked()
	{
		if (Plugin.LanBusy)
		{
			Plu