Decompiled source of Reconnect v1.0.1

Reconnect.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using ExitGames.Client.Photon;
using HarmonyLib;
using Landfall.Network;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using Steamworks;
using UnboundLib.GameModes;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Reconnect")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("Reconnect")]
[assembly: AssemblyTitle("Reconnect")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Reconnect
{
	internal static class LateJoinSync
	{
		internal static object[] Build()
		{
			try
			{
				List<Player> source = PlayerManager.instance.players.Where((Player p) => (Object)(object)p != (Object)null && (Object)(object)p.data != (Object)null && (Object)(object)p.data.view != (Object)null).ToList();
				IGameModeHandler handler = GameModeManager.CurrentHandler;
				int[] array = source.Select((Player p) => p.teamID).Distinct().ToArray();
				return new object[9]
				{
					GameModeManager.CurrentHandlerID ?? "",
					((Object)(object)MapManager.instance != (Object)null) ? MapManager.instance.currentLevelID : (-1),
					source.Select((Player p) => p.data.view.OwnerActorNr).ToArray(),
					source.Select((Player p) => p.playerID).ToArray(),
					source.Select((Player p) => p.teamID).ToArray(),
					source.Select((Player p) => string.Join("\n", p.data.currentCards.Where((CardInfo c) => (Object)(object)c != (Object)null).Select(CardKey))).ToArray(),
					array,
					array.Select((int t) => (handler != null) ? handler.GetTeamScore(t).points : 0).ToArray(),
					array.Select((int t) => (handler != null) ? handler.GetTeamScore(t).rounds : 0).ToArray()
				};
			}
			catch (Exception ex)
			{
				ReconnectPlugin.Log.LogError((object)("Failed to build late-join sync: " + ex));
				return null;
			}
		}

		private static string CardKey(CardInfo c)
		{
			CardInfo val = (((Object)(object)c.sourceCard != (Object)null) ? c.sourceCard : c);
			return ((Object)((Component)val).gameObject).name.Replace("(Clone)", "").Trim() + "|" + val.cardName;
		}

		internal static IEnumerator Apply(object[] d)
		{
			string modeId = (string)d[0];
			int levelId = (int)d[1];
			int[] actors = (int[])d[2];
			int[] pids = (int[])d[3];
			int[] tids = (int[])d[4];
			string[] cards = (string[])d[5];
			int[] teams = (int[])d[6];
			int[] points = (int[])d[7];
			int[] rounds = (int[])d[8];
			Try("game mode", delegate
			{
				if (!string.IsNullOrEmpty(modeId) && modeId != GameModeManager.CurrentHandlerID)
				{
					GameModeManager.SetGameMode(modeId);
				}
			});
			float until = Time.unscaledTime + 10f;
			while (Time.unscaledTime < until && actors.Any((int a) => (Object)(object)FindPlayer(a) == (Object)null))
			{
				yield return null;
			}
			for (int num = 0; num < actors.Length; num++)
			{
				Player p = FindPlayer(actors[num]);
				if ((Object)(object)p == (Object)null)
				{
					ReconnectPlugin.Log.LogWarning((object)$"No character for actor {actors[num]} after rejoin.");
					continue;
				}
				int idx = num;
				Try("ids", delegate
				{
					p.playerID = pids[idx];
					p.teamID = tids[idx];
					p.SetColors();
				});
			}
			if (levelId >= 0 && (Object)(object)MapManager.instance != (Object)null)
			{
				MapManager mm = MapManager.instance;
				Try("map", delegate
				{
					mm.currentLevelID = levelId;
					mm.RPCA_LoadLevel(mm.levels[levelId]);
				});
				until = Time.unscaledTime + 10f;
				while (Time.unscaledTime < until && mm.currentMap == null)
				{
					yield return null;
				}
				Try("map call-in", delegate
				{
					mm.RPCA_CallInNewMapAndMovePlayers(levelId);
				});
			}
			for (int num2 = 0; num2 < actors.Length; num2++)
			{
				Player p2 = FindPlayer(actors[num2]);
				if ((Object)(object)p2 == (Object)null || string.IsNullOrEmpty(cards[num2]))
				{
					continue;
				}
				string[] array = cards[num2].Split(new char[1] { '\n' });
				foreach (string key in array)
				{
					Try("card " + key, delegate
					{
						GiveCard(p2, key);
					});
				}
			}
			Try("score", delegate
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				IGameModeHandler currentHandler = GameModeManager.CurrentHandler;
				if (currentHandler != null)
				{
					for (int i = 0; i < teams.Length; i++)
					{
						currentHandler.SetTeamScore(teams[i], new TeamScore(points[i], rounds[i]));
					}
				}
			});
			Try("state", delegate
			{
				GameManager.instance.isPlaying = true;
				GameManager.instance.battleOngoing = true;
				PlayerManager.instance.SetPlayersSimulated(true);
			});
			ReconnectPlugin.Log.LogInfo((object)"Late-join sync applied.");
		}

		private static Player FindPlayer(int actor)
		{
			return ((IEnumerable<Player>)PlayerManager.instance?.players).FirstOrDefault((Func<Player, bool>)((Player p) => (Object)(object)p != (Object)null && (Object)(object)p.data?.view != (Object)null && p.data.view.OwnerActorNr == actor));
		}

		private static void GiveCard(Player p, string key)
		{
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			string[] parts = key.Split(new char[1] { '|' });
			CardInfo[] cards = CardChoice.instance.cards;
			CardInfo val = ((IEnumerable<CardInfo>)cards).FirstOrDefault((Func<CardInfo, bool>)((CardInfo c) => ((Object)((Component)c).gameObject).name == parts[0])) ?? ((parts.Length > 1) ? ((IEnumerable<CardInfo>)cards).FirstOrDefault((Func<CardInfo, bool>)((CardInfo c) => c.cardName == parts[1])) : null);
			if ((Object)(object)val == (Object)null)
			{
				ReconnectPlugin.Log.LogWarning((object)("Unknown card " + key));
				return;
			}
			GameObject val2 = new GameObject("ReconnectCardHolder");
			val2.SetActive(false);
			try
			{
				ApplyCardStats component = Object.Instantiate<GameObject>(((Component)val).gameObject, val2.transform).GetComponent<ApplyCardStats>();
				AccessTools.Method(typeof(ApplyCardStats), "Start", (Type[])null, (Type[])null)?.Invoke(component, null);
				component.OFFLINE_Pick((Player[])(object)new Player[1] { p });
			}
			finally
			{
				Object.Destroy((Object)(object)val2);
			}
		}

		private static void Try(string what, Action a)
		{
			try
			{
				a();
			}
			catch (Exception ex)
			{
				ReconnectPlugin.Log.LogWarning((object)("Late-join sync step '" + what + "' failed: " + ex.Message));
			}
		}
	}
	internal static class Patches
	{
		[HarmonyPatch]
		private static class RoomOptionsPatch
		{
			private static IEnumerable<MethodBase> TargetMethods()
			{
				return from m in typeof(PhotonNetwork).GetMethods(BindingFlags.Static | BindingFlags.Public)
					where (m.Name == "CreateRoom" || m.Name == "JoinOrCreateRoom" || m.Name == "JoinRandomOrCreateRoom") && m.GetParameters().Any((ParameterInfo p) => p.ParameterType == typeof(RoomOptions))
					select m;
			}

			private static void Prefix(object[] __args)
			{
				foreach (RoomOptions item in __args.OfType<RoomOptions>())
				{
					item.PlayerTtl = ReconnectPlugin.ReconnectWindowSeconds.Value * 1000;
					item.PublishUserId = true;
				}
			}
		}

		[HarmonyPatch]
		private static class PlayerLeftPatch
		{
			private static MethodBase TargetMethod()
			{
				return Container("InRoomCallbacksContainer", "OnPlayerLeftRoom");
			}

			private static bool Prefix(IEnumerable<IInRoomCallbacks> __instance, Player otherPlayer)
			{
				if ((Object)(object)M == (Object)null || otherPlayer == null)
				{
					return true;
				}
				if (otherPlayer.IsInactive && ReconnectManager.MatchActiveSnapshot && !M.IsAbandoned(otherPlayer))
				{
					M.OnRemoteInactive(otherPlayer);
					Dispatch(__instance, delegate(IInRoomCallbacks t)
					{
						t.OnPlayerLeftRoom(otherPlayer);
					}, photonInternalOnly: true);
					return false;
				}
				if (!otherPlayer.IsInactive && M.IsWaitingFor(otherPlayer.ActorNumber))
				{
					M.OnRemoteFinalLeave(otherPlayer);
				}
				return true;
			}
		}

		[HarmonyPatch]
		private static class PlayerEnteredPatch
		{
			private static MethodBase TargetMethod()
			{
				return Container("InRoomCallbacksContainer", "OnPlayerEnteredRoom");
			}

			private static bool Prefix(IEnumerable<IInRoomCallbacks> __instance, Player newPlayer)
			{
				if ((Object)(object)M == (Object)null || newPlayer == null)
				{
					return true;
				}
				if (!M.IsWaitingFor(newPlayer.ActorNumber) && !newPlayer.HasRejoined)
				{
					return true;
				}
				Dispatch(__instance, delegate(IInRoomCallbacks t)
				{
					t.OnPlayerEnteredRoom(newPlayer);
				}, photonInternalOnly: true);
				if (M.IsAbandoned(newPlayer))
				{
					if (PhotonNetwork.IsMasterClient)
					{
						PhotonNetwork.CloseConnection(newPlayer);
					}
					return false;
				}
				M.OnRemoteRejoined(newPlayer);
				return false;
			}
		}

		[HarmonyPatch(typeof(PhotonNetwork), "LeftRoomCleanup")]
		private static class LeftRoomCleanupPatch
		{
			private static bool Prefix()
			{
				if (ReconnectManager.PreserveRoomState)
				{
					return false;
				}
				if ((Object)(object)M != (Object)null && !ReconnectManager.IntentionalLeave && ReconnectManager.MatchActiveSnapshot && !PhotonNetwork.OfflineMode)
				{
					M.BeginLocalReconnect();
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(PhotonNetwork), "LeaveRoom")]
		private static class LeaveRoomPatch
		{
			private static void Prefix(ref bool becomeInactive)
			{
				ReconnectManager.IntentionalLeave = true;
				if (!ReconnectManager.LocalReconnecting)
				{
					becomeInactive = false;
				}
			}
		}

		[HarmonyPatch(typeof(PhotonNetwork), "Disconnect")]
		private static class DisconnectPatch
		{
			private static void Prefix()
			{
				ReconnectManager.IntentionalLeave = true;
			}
		}

		[HarmonyPatch(typeof(PhotonNetwork), "JoinRoom")]
		private static class JoinRoomPatch
		{
			private static void Prefix(string roomName)
			{
				if (roomName != ReconnectManager.LastAttemptedRoom)
				{
					GameJoinRoomFailedPatch.Reset();
				}
				ReconnectManager.LastAttemptedRoom = roomName;
			}
		}

		[HarmonyPatch(typeof(NetworkConnectionHandler), "OnDisconnected")]
		private static class GameOnDisconnectedPatch
		{
			private static bool Prefix()
			{
				if (!ReconnectManager.LocalReconnecting)
				{
					return !ReconnectManager.PreserveRoomState;
				}
				return false;
			}
		}

		[HarmonyPatch]
		private static class LeftRoomPatch
		{
			private static MethodBase TargetMethod()
			{
				return Container("MatchMakingCallbacksContainer", "OnLeftRoom");
			}

			private static bool Prefix(IEnumerable<IMatchmakingCallbacks> __instance)
			{
				if (!ReconnectManager.LocalReconnecting && !ReconnectManager.PreserveRoomState)
				{
					return true;
				}
				Dispatch(__instance, delegate(IMatchmakingCallbacks t)
				{
					t.OnLeftRoom();
				}, photonInternalOnly: true);
				return false;
			}
		}

		[HarmonyPatch]
		private static class JoinedRoomPatch
		{
			private static MethodBase TargetMethod()
			{
				return Container("MatchMakingCallbacksContainer", "OnJoinedRoom");
			}

			private static bool Prefix(IEnumerable<IMatchmakingCallbacks> __instance)
			{
				if ((Object)(object)M == (Object)null)
				{
					return true;
				}
				if (ReconnectManager.LocalReconnecting)
				{
					Dispatch(__instance, delegate(IMatchmakingCallbacks t)
					{
						t.OnJoinedRoom();
					}, photonInternalOnly: true);
					M.OnLocalRejoined();
					return false;
				}
				if (ReconnectPlugin.AllowLateRejoin.Value && (ReconnectManager.LateRejoinPending || ReconnectManager.RoomSaysMatchInProgress()))
				{
					Dispatch(__instance, delegate(IMatchmakingCallbacks t)
					{
						t.OnJoinedRoom();
					}, photonInternalOnly: true);
					M.BeginLateRejoin();
					return false;
				}
				ReconnectManager.LateRejoinPending = false;
				return true;
			}
		}

		[HarmonyPatch]
		private static class JoinRoomFailedPatch
		{
			private static MethodBase TargetMethod()
			{
				return Container("MatchMakingCallbacksContainer", "OnJoinRoomFailed");
			}

			private static bool Prefix(short returnCode, string message)
			{
				if (ReconnectManager.LocalReconnecting)
				{
					M?.OnLocalRejoinFailed(returnCode, message);
					return false;
				}
				if (ReconnectManager.LateRejoinPending)
				{
					ReconnectPlugin.Log.LogWarning((object)$"Late rejoin failed ({returnCode}): {message}");
					ReconnectManager.LateRejoinPending = false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(NetworkConnectionHandler), "OnJoinRoomFailed")]
		private static class GameJoinRoomFailedPatch
		{
			private static string rejoinTriedFor;

			private static bool Prefix(short returnCode, string message)
			{
				string lastAttemptedRoom = ReconnectManager.LastAttemptedRoom;
				ReconnectPlugin.Log.LogInfo((object)$"Joining room '{lastAttemptedRoom}' failed ({returnCode}): {message}");
				if (!ReconnectPlugin.AllowLateRejoin.Value || string.IsNullOrEmpty(lastAttemptedRoom))
				{
					return true;
				}
				if (returnCode == 32758 || rejoinTriedFor == lastAttemptedRoom)
				{
					return true;
				}
				rejoinTriedFor = lastAttemptedRoom;
				ReconnectPlugin.Log.LogInfo((object)("Trying to reclaim our old slot in '" + lastAttemptedRoom + "'."));
				ReconnectManager.LateRejoinPending = true;
				if (!PhotonNetwork.RejoinRoom(lastAttemptedRoom))
				{
					ReconnectManager.LateRejoinPending = false;
					return true;
				}
				return false;
			}

			internal static void Reset()
			{
				rejoinTriedFor = null;
			}
		}

		[HarmonyPatch(typeof(PhotonNetwork), "OnEvent")]
		private static class ReplayFilterPatch
		{
			private const byte PunInstantiation = 202;

			private const byte PunRpc = 200;

			private static bool Prefix(EventData photonEvent)
			{
				if (photonEvent.Code == 202)
				{
					object customData = photonEvent.CustomData;
					Hashtable val = (Hashtable)((customData is Hashtable) ? customData : null);
					if (val != null && ((Dictionary<object, object>)(object)val).TryGetValue((object)(byte)7, out object value) && value is int num && (Object)(object)PhotonView.Find(num) != (Object)null)
					{
						return false;
					}
				}
				if (photonEvent.Code == 200 && Time.unscaledTime < ReconnectManager.DropReplayedRpcsUntil)
				{
					return false;
				}
				return true;
			}
		}

		[HarmonyPatch(typeof(TimeHandler), "Update")]
		private static class TimeHandlerPatch
		{
			private static void Postfix()
			{
				if (!((Object)(object)M == (Object)null) && M.IsPaused)
				{
					TimeHandler.timeScale = 0f;
					TimeHandler.deltaTime = 0f;
					TimeHandler.fixedDeltaTime = 0f;
					Time.timeScale = 0f;
				}
			}
		}

		private static readonly MethodInfo UpdateCallbackTargets = AccessTools.Method(typeof(LoadBalancingClient), "UpdateCallbackTargets", (Type[])null, (Type[])null);

		private static readonly FieldInfo InRoomTargetsField = AccessTools.Field(typeof(LoadBalancingClient), "InRoomCallbackTargets");

		private static ReconnectManager M => ReconnectManager.Instance;

		private static bool IsPhotonInternal(object target)
		{
			return (target.GetType().Namespace ?? "").StartsWith("Photon", StringComparison.Ordinal);
		}

		internal static void Dispatch<T>(IEnumerable<T> targets, Action<T> call, bool photonInternalOnly)
		{
			try
			{
				UpdateCallbackTargets?.Invoke(PhotonNetwork.NetworkingClient, null);
			}
			catch
			{
			}
			foreach (T item in targets.ToList())
			{
				if (IsPhotonInternal(item) == photonInternalOnly)
				{
					try
					{
						call(item);
					}
					catch (Exception arg)
					{
						ReconnectPlugin.Log.LogError((object)$"Callback {item.GetType().Name} threw: {arg}");
					}
				}
			}
		}

		internal static void DispatchPlayerLeftToGame(Player p)
		{
			if (InRoomTargetsField?.GetValue(PhotonNetwork.NetworkingClient) is IEnumerable<IInRoomCallbacks> targets)
			{
				Dispatch(targets, delegate(IInRoomCallbacks t)
				{
					t.OnPlayerLeftRoom(p);
				}, photonInternalOnly: false);
			}
		}

		private static MethodBase Container(string type, string method)
		{
			return AccessTools.Method(AccessTools.TypeByName("Photon.Realtime." + type), method, (Type[])null, (Type[])null);
		}
	}
	[BepInPlugin("com.yofakeparent.rounds.reconnect", "Reconnect", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInProcess("Rounds.exe")]
	public class ReconnectPlugin : BaseUnityPlugin
	{
		public const string ModId = "com.yofakeparent.rounds.reconnect";

		public const string ModName = "Reconnect";

		public const string Version = "1.0.1";

		internal static ManualLogSource Log;

		internal static ConfigEntry<int> ReconnectWindowSeconds;

		internal static ConfigEntry<bool> UseSteamIdAsPhotonUserId;

		internal static ConfigEntry<bool> PauseWhileWaiting;

		internal static ConfigEntry<bool> AllowLateRejoin;

		private void Awake()
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			ReconnectWindowSeconds = ((BaseUnityPlugin)this).Config.Bind<int>("General", "ReconnectWindowSeconds", 300, new ConfigDescription("How long (seconds) a disconnected player's slot is held open. Only the host's value matters. Photon Cloud caps this at 300.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(15, 300), Array.Empty<object>()));
			UseSteamIdAsPhotonUserId = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "UseSteamIdAsPhotonUserId", true, "Identify players by Steam ID so a player who restarted the game can claim their old slot. Turn off only if you test with two game instances on the same Steam account.");
			PauseWhileWaiting = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "PauseWhileWaiting", true, "Freeze the match while a player is reconnecting.");
			AllowLateRejoin = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "AllowLateRejoin", true, "EXPERIMENTAL: let a player who fully restarted ROUNDS rejoin through a Steam invite. The host re-sends map, cards and score. In-process reconnects (Wi-Fi drop, timeout) work without this.");
			new Harmony("com.yofakeparent.rounds.reconnect").PatchAll(typeof(ReconnectPlugin).Assembly);
			((Component)this).gameObject.AddComponent<ReconnectManager>();
			Log.LogInfo((object)"Reconnect 1.0.1 loaded");
		}
	}
	public class ReconnectManager : MonoBehaviour
	{
		private class WaitingPlayer
		{
			public int Actor;

			public string UserId;

			public string Name;

			public float Since;

			public bool WasMaster;

			public bool Rejoined;

			public float RejoinedAt;
		}

		private const byte EvContinue = 171;

		private const byte EvInvite = 172;

		private const byte EvHello = 173;

		private const byte EvSyncData = 175;

		private const byte EvReady = 176;

		internal const string RoomInMatchKey = "rc_inMatch";

		private readonly Dictionary<int, WaitingPlayer> waiting = new Dictionary<int, WaitingPlayer>();

		private readonly HashSet<string> abandonedUserIds = new HashSet<string>();

		internal static bool IntentionalLeave;

		internal static bool PreserveRoomState;

		internal static bool LocalReconnecting;

		internal static bool LateRejoinPending;

		internal static bool AwaitingSync;

		internal static float DropReplayedRpcsUntil;

		internal static bool MatchActiveSnapshot;

		internal static string LastAttemptedRoom;

		private static int lastMasterActor = -1;

		private static int lastRoomTtlMs;

		private float localLostAt;

		private float syncStartedAt;

		private int attempts;

		private string localStatus = "";

		private bool lastPublishedInMatch;

		private bool pausedByUs;

		private bool prevLockInput;

		private LoadBalancingClient subscribedClient;

		private string inviteStatus = "";

		private GUIStyle titleStyle;

		private GUIStyle bodyStyle;

		private GUIStyle buttonStyle;

		private GUIStyle boxStyle;

		private Texture2D panelTex;

		private Texture2D dimTex;

		public static ReconnectManager Instance { get; private set; }

		public bool IsPaused
		{
			get
			{
				if (ReconnectPlugin.PauseWhileWaiting.Value)
				{
					if (waiting.Count <= 0 && !LocalReconnecting)
					{
						return AwaitingSync;
					}
					return true;
				}
				return false;
			}
		}

		private float LocalWindowSeconds => Mathf.Max(15f, (float)((lastRoomTtlMs > 0) ? lastRoomTtlMs : (ReconnectPlugin.ReconnectWindowSeconds.Value * 1000)) / 1000f);

		internal static ClientSteamLobby SteamLobby => Traverse.Create(typeof(NetworkConnectionHandler)).Field("m_SteamLobby").GetValue<ClientSteamLobby>();

		private void Awake()
		{
			Instance = this;
		}

		private void EnsureEventSubscription()
		{
			LoadBalancingClient networkingClient = PhotonNetwork.NetworkingClient;
			if (networkingClient != subscribedClient)
			{
				if (subscribedClient != null)
				{
					subscribedClient.EventReceived -= OnPhotonEvent;
				}
				subscribedClient = networkingClient;
				if (networkingClient != null)
				{
					networkingClient.EventReceived += OnPhotonEvent;
				}
			}
		}

		private void OnDisable()
		{
			if (subscribedClient != null)
			{
				subscribedClient.EventReceived -= OnPhotonEvent;
			}
			subscribedClient = null;
		}

		private void Update()
		{
			EnsureEventSubscription();
			EnsureSteamUserId();
			HandleHotkeys();
			if (PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode)
			{
				IntentionalLeave = false;
				lastMasterActor = ((PhotonNetwork.MasterClient != null) ? PhotonNetwork.MasterClient.ActorNumber : (-1));
				lastRoomTtlMs = PhotonNetwork.CurrentRoom.PlayerTtl;
				MatchActiveSnapshot = lastRoomTtlMs > 0 && (Object)(object)GameManager.instance != (Object)null && GameManager.instance.isPlaying;
				PublishInMatchFlag();
			}
			else if (!LocalReconnecting)
			{
				MatchActiveSnapshot = false;
				if (!PhotonNetwork.InRoom && waiting.Count > 0)
				{
					waiting.Clear();
				}
			}
			foreach (WaitingPlayer item in waiting.Values.Where((WaitingPlayer w) => w.Rejoined && Time.unscaledTime - w.RejoinedAt > 25f).ToList())
			{
				ReconnectPlugin.Log.LogWarning((object)(item.Name + " rejoined but never finished syncing; resuming."));
				waiting.Remove(item.Actor);
			}
			if (AwaitingSync && Time.unscaledTime - syncStartedAt > 30f)
			{
				AwaitingSync = false;
				GiveUpLocal("The host never sent the match state.");
			}
			UpdatePauseInput();
		}

		private static void EnsureSteamUserId()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			if (ReconnectPlugin.UseSteamIdAsPhotonUserId.Value && !PhotonNetwork.IsConnected && SteamManager.Initialized)
			{
				string text = SteamUser.GetSteamID().m_SteamID.ToString();
				if (PhotonNetwork.AuthValues == null)
				{
					PhotonNetwork.AuthValues = new AuthenticationValues(text);
				}
				else if (PhotonNetwork.AuthValues.UserId != text)
				{
					PhotonNetwork.AuthValues.UserId = text;
				}
			}
		}

		private void PublishInMatchFlag()
		{
			//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_006d: Expected O, but got Unknown
			//IL_0074: Expected O, but got Unknown
			if (!PhotonNetwork.IsMasterClient)
			{
				lastPublishedInMatch = false;
				return;
			}
			bool matchActiveSnapshot = MatchActiveSnapshot;
			object value = null;
			((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"rc_inMatch", out value);
			if (!(value is bool flag) || flag != matchActiveSnapshot || lastPublishedInMatch != matchActiveSnapshot)
			{
				lastPublishedInMatch = matchActiveSnapshot;
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Hashtable val = new Hashtable();
				((Dictionary<object, object>)val).Add((object)"rc_inMatch", (object)matchActiveSnapshot);
				currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null);
			}
		}

		internal static bool RoomSaysMatchInProgress()
		{
			if (PhotonNetwork.CurrentRoom == null)
			{
				return false;
			}
			bool flag = default(bool);
			int num;
			if (((Dictionary<object, object>)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties).TryGetValue((object)"rc_inMatch", out object value))
			{
				if (value is bool)
				{
					flag = (bool)value;
					num = 1;
				}
				else
				{
					num = 0;
				}
			}
			else
			{
				num = 0;
			}
			return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
		}

		private void UpdatePauseInput()
		{
			if (IsPaused)
			{
				if (!pausedByUs)
				{
					prevLockInput = GameManager.lockInput;
					pausedByUs = true;
				}
				GameManager.lockInput = true;
			}
			else if (pausedByUs)
			{
				GameManager.lockInput = prevLockInput;
				pausedByUs = false;
			}
		}

		internal bool IsWaitingFor(int actor)
		{
			return waiting.ContainsKey(actor);
		}

		internal bool IsAbandoned(Player p)
		{
			if (!string.IsNullOrEmpty(p.UserId))
			{
				return abandonedUserIds.Contains(p.UserId);
			}
			return false;
		}

		internal void OnRemoteInactive(Player p)
		{
			inviteStatus = "";
			waiting[p.ActorNumber] = new WaitingPlayer
			{
				Actor = p.ActorNumber,
				UserId = p.UserId,
				Name = NameOf(p),
				Since = Time.unscaledTime,
				WasMaster = (p.ActorNumber == lastMasterActor)
			};
			ReconnectPlugin.Log.LogInfo((object)$"{NameOf(p)} (actor {p.ActorNumber}, id {p.UserId}) disconnected; holding their slot.");
		}

		internal void OnRemoteFinalLeave(Player p)
		{
			if (waiting.Remove(p.ActorNumber))
			{
				ReconnectPlugin.Log.LogInfo((object)(NameOf(p) + "'s reconnect window ran out."));
			}
		}

		internal void OnRemoteRejoined(Player p)
		{
			if (!waiting.TryGetValue(p.ActorNumber, out var value))
			{
				value = new WaitingPlayer
				{
					Actor = p.ActorNumber,
					UserId = p.UserId,
					Name = NameOf(p),
					Since = Time.unscaledTime
				};
				waiting[p.ActorNumber] = value;
			}
			value.Rejoined = true;
			value.RejoinedAt = Time.unscaledTime;
			ReconnectPlugin.Log.LogInfo((object)(value.Name + " is back in the room, waiting for them to resync."));
			if (value.WasMaster && PhotonNetwork.IsMasterClient)
			{
				PhotonNetwork.SetMasterClient(p);
			}
			ClientSteamLobby steamLobby = SteamLobby;
			if (steamLobby != null)
			{
				steamLobby.HideLobby();
			}
		}

		private void ContinueWithout(int actor)
		{
			ReconnectPlugin.Log.LogInfo((object)$"Continue without actor {actor} clicked.");
			HandleContinue(actor);
			RaiseOthers(171, actor);
		}

		private void HandleHotkeys()
		{
			if (waiting.Count == 0 || !PhotonNetwork.InRoom)
			{
				return;
			}
			WaitingPlayer waitingPlayer = waiting.Values.FirstOrDefault((WaitingPlayer w) => !w.Rejoined);
			if (waitingPlayer != null)
			{
				if (Input.GetKeyDown((KeyCode)290))
				{
					ContinueWithout(waitingPlayer.Actor);
				}
				else if (Input.GetKeyDown((KeyCode)291))
				{
					Invite(waitingPlayer);
				}
			}
		}

		private void HandleContinue(int actor)
		{
			if (waiting.TryGetValue(actor, out var value))
			{
				waiting.Remove(actor);
				if (!string.IsNullOrEmpty(value.UserId))
				{
					abandonedUserIds.Add(value.UserId);
				}
				ReconnectPlugin.Log.LogInfo((object)("Continuing without " + value.Name + "."));
				Room currentRoom = PhotonNetwork.CurrentRoom;
				Player val = ((currentRoom != null) ? currentRoom.GetPlayer(actor) : null);
				if (val != null)
				{
					Patches.DispatchPlayerLeftToGame(val);
				}
				if (PhotonNetwork.IsMasterClient)
				{
					((MonoBehaviour)this).StartCoroutine(DestroyObjectsNextFrame(actor));
				}
			}
		}

		private IEnumerator DestroyObjectsNextFrame(int actor)
		{
			yield return null;
			try
			{
				PhotonNetwork.DestroyPlayerObjects(actor);
			}
			catch (Exception ex)
			{
				ReconnectPlugin.Log.LogWarning((object)$"Could not clean up actor {actor}: {ex.Message}");
			}
		}

		private void Invite(WaitingPlayer w)
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			ReconnectPlugin.Log.LogInfo((object)("Invite back " + w.Name + " clicked."));
			ClientSteamLobby steamLobby = SteamLobby;
			if (steamLobby == null || !steamLobby.IsInsideLobby)
			{
				inviteStatus = "No Steam lobby to invite into.";
				ReconnectPlugin.Log.LogWarning((object)inviteStatus);
				return;
			}
			steamLobby.OpenLobby();
			RaiseOthers(172, w.Actor);
			SteamFriends.ActivateGameOverlayInviteDialog(steamLobby.CurrentLobby);
			inviteStatus = "Steam invite page opened - invite " + w.Name + ". (Needs the Steam overlay enabled.)";
		}

		internal void BeginLocalReconnect()
		{
			if (!LocalReconnecting)
			{
				LocalReconnecting = true;
				PreserveRoomState = true;
				localLostAt = Time.unscaledTime;
				attempts = 0;
				localStatus = "Connection lost";
				ReconnectPlugin.Log.LogInfo((object)"Lost connection mid-match; keeping game state and reconnecting.");
				((MonoBehaviour)this).StartCoroutine(LocalReconnectLoop());
			}
		}

		private IEnumerator LocalReconnectLoop()
		{
			yield return (object)new WaitForSecondsRealtime(0.5f);
			while (LocalReconnecting && Time.unscaledTime - localLostAt < LocalWindowSeconds)
			{
				if ((int)PhotonNetwork.NetworkClientState == 14 || (int)PhotonNetwork.NetworkClientState == 0)
				{
					attempts++;
					localStatus = $"Reconnecting (attempt {attempts})";
					if (!PhotonNetwork.ReconnectAndRejoin())
					{
						ReconnectPlugin.Log.LogWarning((object)"ReconnectAndRejoin refused to start; will retry.");
					}
				}
				float started = Time.unscaledTime;
				while (LocalReconnecting && Time.unscaledTime - started < 8f && (int)PhotonNetwork.NetworkClientState != 14)
				{
					yield return null;
				}
				if (LocalReconnecting)
				{
					yield return (object)new WaitForSecondsRealtime(1.5f);
				}
			}
			if (LocalReconnecting)
			{
				GiveUpLocal("Couldn't get back into the match.");
			}
		}

		internal void OnLocalRejoined()
		{
			LocalReconnecting = false;
			PreserveRoomState = false;
			DropReplayedRpcsUntil = Time.unscaledTime + 2.5f;
			ReconnectPlugin.Log.LogInfo((object)$"Rejoined room after {attempts} attempt(s).");
			RaiseOthers(173, false);
		}

		internal void OnLocalRejoinFailed(short code, string message)
		{
			ReconnectPlugin.Log.LogWarning((object)$"Rejoin failed ({code}): {message}");
			if (code == 32748 || code == 32758)
			{
				GiveUpLocal("Your spot in the match has expired.");
			}
		}

		internal void BeginLateRejoin()
		{
			LateRejoinPending = false;
			AwaitingSync = true;
			syncStartedAt = Time.unscaledTime;
			localStatus = "Rejoining match";
			ReconnectPlugin.Log.LogInfo((object)"Rejoined a match in progress after a restart; requesting state from host.");
			try
			{
				MainMenuHandler instance = MainMenuHandler.instance;
				if (instance != null)
				{
					instance.Close();
				}
			}
			catch
			{
			}
			try
			{
				CharacterCreatorHandler instance2 = CharacterCreatorHandler.instance;
				if (instance2 != null)
				{
					instance2.CloseMenus();
				}
			}
			catch
			{
			}
			try
			{
				LoadingScreen instance3 = LoadingScreen.instance;
				if (instance3 != null)
				{
					instance3.StopLoading();
				}
			}
			catch
			{
			}
			RaiseOthers(173, true);
		}

		private void GiveUpLocal(string reason)
		{
			ReconnectPlugin.Log.LogWarning((object)("Giving up reconnect: " + reason));
			LocalReconnecting = false;
			AwaitingSync = false;
			PreserveRoomState = false;
			IntentionalLeave = true;
			try
			{
				if (PhotonNetwork.IsConnected)
				{
					PhotonNetwork.Disconnect();
				}
				AccessTools.Method(typeof(PhotonNetwork), "LeftRoomCleanup", (Type[])null, (Type[])null)?.Invoke(null, null);
			}
			catch (Exception ex)
			{
				ReconnectPlugin.Log.LogWarning((object)ex);
			}
			NetworkConnectionHandler instance = NetworkConnectionHandler.instance;
			MethodInfo methodInfo = AccessTools.Method(typeof(NetworkConnectionHandler), "DoDisconnect", (Type[])null, (Type[])null);
			if ((Object)(object)instance != (Object)null && methodInfo != null)
			{
				((MonoBehaviour)instance).StartCoroutine((IEnumerator)methodInfo.Invoke(instance, new object[2] { "DISCONNECTED", reason }));
			}
			else if (instance != null)
			{
				instance.NetworkRestart();
			}
		}

		private void OnPhotonEvent(EventData ev)
		{
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Expected O, but got Unknown
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			switch (ev.Code)
			{
			case 171:
				HandleContinue((int)ev.CustomData);
				break;
			case 172:
			{
				ClientSteamLobby steamLobby = SteamLobby;
				if (steamLobby != null)
				{
					steamLobby.OpenLobby();
				}
				break;
			}
			case 173:
			{
				object customData = ev.CustomData;
				bool flag = default(bool);
				int num;
				if (customData is bool)
				{
					flag = (bool)customData;
					num = 1;
				}
				else
				{
					num = 0;
				}
				bool flag2 = (byte)((uint)num & (flag ? 1u : 0u)) != 0;
				if (!waiting.TryGetValue(ev.Sender, out var value2))
				{
					break;
				}
				if (!flag2)
				{
					waiting.Remove(ev.Sender);
					ReconnectPlugin.Log.LogInfo((object)(value2.Name + " reconnected. Resuming."));
				}
				else if (PhotonNetwork.IsMasterClient)
				{
					object[] array = LateJoinSync.Build();
					if (array != null)
					{
						RaiseEventOptions val = new RaiseEventOptions();
						val.TargetActors = new int[1] { ev.Sender };
						PhotonNetwork.RaiseEvent((byte)175, (object)array, val, SendOptions.SendReliable);
					}
				}
				break;
			}
			case 175:
				if (AwaitingSync && ev.CustomData is object[] payload)
				{
					((MonoBehaviour)this).StartCoroutine(ApplySync(payload));
				}
				break;
			case 176:
			{
				if (waiting.TryGetValue(ev.Sender, out var value))
				{
					waiting.Remove(ev.Sender);
					ReconnectPlugin.Log.LogInfo((object)(value.Name + " finished syncing. Resuming."));
				}
				break;
			}
			case 174:
				break;
			}
		}

		private IEnumerator ApplySync(object[] payload)
		{
			localStatus = "Syncing match state";
			yield return LateJoinSync.Apply(payload);
			AwaitingSync = false;
			RaiseOthers(176, null);
		}

		private static void RaiseAll(byte code, object content)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			PhotonNetwork.RaiseEvent(code, content, new RaiseEventOptions
			{
				Receivers = (ReceiverGroup)1
			}, SendOptions.SendReliable);
		}

		private static void RaiseOthers(byte code, object content)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			PhotonNetwork.RaiseEvent(code, content, new RaiseEventOptions
			{
				Receivers = (ReceiverGroup)0
			}, SendOptions.SendReliable);
		}

		private static string NameOf(Player p)
		{
			if (!string.IsNullOrEmpty(p.NickName))
			{
				return p.NickName;
			}
			return $"Player {p.ActorNumber}";
		}

		private float RemainingSeconds(WaitingPlayer w)
		{
			int num = ((PhotonNetwork.CurrentRoom != null) ? PhotonNetwork.CurrentRoom.PlayerTtl : lastRoomTtlMs);
			return Mathf.Max(0f, (float)num / 1000f - (Time.unscaledTime - w.Since));
		}

		private void BuildStyles()
		{
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_0080: Expected O, but got Unknown
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Expected O, but got Unknown
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Expected O, but got Unknown
			if (titleStyle == null)
			{
				panelTex = MakeTex(new Color(0.08f, 0.08f, 0.1f, 0.95f));
				dimTex = MakeTex(new Color(0f, 0f, 0f, 0.45f));
				GUIStyle val = new GUIStyle();
				val.normal.background = panelTex;
				val.padding = new RectOffset(24, 24, 20, 20);
				boxStyle = val;
				GUIStyle val2 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 30,
					fontStyle = (FontStyle)1,
					alignment = (TextAnchor)4
				};
				val2.normal.textColor = Color.white;
				titleStyle = val2;
				GUIStyle val3 = new GUIStyle(GUI.skin.label)
				{
					fontSize = 20,
					alignment = (TextAnchor)4,
					wordWrap = true
				};
				val3.normal.textColor = new Color(0.85f, 0.85f, 0.9f);
				bodyStyle = val3;
				buttonStyle = new GUIStyle(GUI.skin.button)
				{
					fontSize = 20,
					fixedHeight = 44f
				};
			}
		}

		private static Texture2D MakeTex(Color c)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			Texture2D val = new Texture2D(1, 1);
			val.SetPixel(0, 0, c);
			val.Apply();
			return val;
		}

		private void OnGUI()
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Unknown result type (might be due to invalid IL or missing references)
			bool flag = waiting.Count > 0 && PhotonNetwork.InRoom;
			if (!flag && !LocalReconnecting && !AwaitingSync)
			{
				return;
			}
			BuildStyles();
			Cursor.visible = true;
			Cursor.lockState = (CursorLockMode)0;
			GUI.depth = -1000;
			float num = (float)Screen.height / 1080f;
			GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(num, num, 1f));
			float num2 = (float)Screen.width / num;
			float num3 = 1080f;
			GUI.DrawTexture(new Rect(0f, 0f, num2, num3), (Texture)(object)dimTex);
			float num4 = (flag ? (190f + (float)waiting.Count * 110f) : 220f);
			GUILayout.BeginArea(new Rect((num2 - 620f) / 2f, (num3 - num4) / 2f, 620f, num4), boxStyle);
			if (LocalReconnecting)
			{
				GUILayout.Label("CONNECTION LOST", titleStyle, Array.Empty<GUILayoutOption>());
				float num5 = Mathf.Max(0f, LocalWindowSeconds - (Time.unscaledTime - localLostAt));
				GUILayout.Label($"{localStatus}... {Mathf.CeilToInt(num5)}s left", bodyStyle, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				if (GUILayout.Button("Give up and return to menu", buttonStyle, Array.Empty<GUILayoutOption>()))
				{
					GiveUpLocal("You left the match.");
				}
			}
			else if (AwaitingSync)
			{
				GUILayout.Label("REJOINING MATCH", titleStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label(localStatus + "...", bodyStyle, Array.Empty<GUILayoutOption>());
				GUILayout.FlexibleSpace();
				if (GUILayout.Button("Cancel", buttonStyle, Array.Empty<GUILayoutOption>()))
				{
					GiveUpLocal("You left the match.");
				}
			}
			else
			{
				GUILayout.Label("GAME PAUSED", titleStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Space(6f);
				foreach (WaitingPlayer item in waiting.Values.ToList())
				{
					string text = (item.Rejoined ? "is back, syncing..." : $"disconnected - {Mathf.CeilToInt(RemainingSeconds(item))}s to rejoin");
					GUILayout.Label(item.Name + " " + text, bodyStyle, Array.Empty<GUILayoutOption>());
					GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
					GUI.enabled = !item.Rejoined;
					if (GUILayout.Button("Continue without them (F9)", buttonStyle, Array.Empty<GUILayoutOption>()))
					{
						ContinueWithout(item.Actor);
					}
					if (GUILayout.Button("Invite back (F10)", buttonStyle, Array.Empty<GUILayoutOption>()))
					{
						Invite(item);
					}
					GUI.enabled = true;
					GUILayout.EndHorizontal();
					GUILayout.Space(10f);
				}
				if (!string.IsNullOrEmpty(inviteStatus))
				{
					GUILayout.Label(inviteStatus, bodyStyle, Array.Empty<GUILayoutOption>());
				}
			}
			GUILayout.EndArea();
			GUI.matrix = Matrix4x4.identity;
		}
	}
}