using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;
[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("Reconnects to the LAN server and rejoins the running match after a dropped connection.")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+cbd49b0008e7eb00b593d7bcd887cbeb17ccfd7f")]
[assembly: AssemblyProduct("ROUNDS LAN Rejoin")]
[assembly: AssemblyTitle("RoundsLanRejoin")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace RoundsLanRejoin;
[BepInPlugin("tiago.rounds.rejoin", "ROUNDS LAN Rejoin", "0.1.0")]
public class Plugin : BaseUnityPlugin
{
public const string Guid = "tiago.rounds.rejoin";
public const string PluginVersion = "0.1.0";
internal static ManualLogSource Log;
internal static Plugin Instance;
internal static ConfigEntry<bool> Enabled;
internal static ConfigEntry<string> Address;
internal static ConfigEntry<int> Port;
internal static ConfigEntry<bool> ReadLanModConfig;
internal static ConfigEntry<bool> AutoRejoin;
internal static ConfigEntry<int> MaxAttempts;
internal static ConfigEntry<float> RetryDelay;
internal static ConfigEntry<float> ConnectWait;
internal static ConfigEntry<float> JoinWait;
internal static ConfigEntry<bool> PublishMatchState;
internal static ConfigEntry<bool> LoadMatchLevel;
internal static ConfigEntry<bool> AutoSpawn;
internal static ConfigEntry<bool> KeepMatchWhenPlayerLeaves;
internal static ConfigEntry<bool> PanelEnabled;
internal static ConfigEntry<string> PanelKey;
internal static string SavedRoom;
internal static int SavedLevel = -1;
internal static string Status = "idle";
internal static int Attempts;
private static bool _rejoining;
private static bool _leaveExpected;
private bool _dialFailed;
private static bool _captured;
private static string _savedServer;
private static string _savedRegion;
private static string _savedAppId;
private static int _savedPort;
private static bool _savedUseNameServer;
private float _nextPublish;
private string _published;
private bool _panelVisible = true;
private KeyCode _panelKey = (KeyCode)290;
private string _typedRoom = "rounds-lan";
private bool _warned;
private static GUIStyle _small;
private void Awake()
{
Instance = this;
try
{
AwakeCore();
}
catch (Exception ex)
{
((BaseUnityPlugin)this).Logger.LogError((object)("[REJOIN] startup failed, the mod is inert until this is fixed: " + ex));
}
}
private void AwakeCore()
{
//IL_0229: Unknown result type (might be due to invalid IL or missing references)
//IL_022e: 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. Off means the mod loads, logs and changes nothing.");
Address = ((BaseUnityPlugin)this).Config.Bind<string>("Server", "Address", "127.0.0.1", "The LAN server to reconnect to. Left at 127.0.0.1 it means this PC is the host, which is only right for the hosting player: everyone else needs the host's address here.");
Port = ((BaseUnityPlugin)this).Config.Bind<int>("Server", "Port", 5055, "The LAN server's port.");
ReadLanModConfig = ((BaseUnityPlugin)this).Config.Bind<bool>("Server", "ReadLanModConfig", true, "When ROUNDS LAN Photon is installed, take its Server/Address and Server/Port from its config file, which also carries the host address it discovered. Set false to use the two values above instead.");
AutoRejoin = ((BaseUnityPlugin)this).Config.Bind<bool>("Rejoin", "AutoRejoin", true, "Reconnect and rejoin by itself after the connection drops. Off means the panel button is the only way back.");
MaxAttempts = ((BaseUnityPlugin)this).Config.Bind<int>("Rejoin", "MaxAttempts", 3, "How many times to try before handing the game back to its own error handling.");
RetryDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Rejoin", "RetryDelaySeconds", 3f, "Wait before dialling again, so a server that is still tearing the old session down has a moment to finish.");
ConnectWait = ((BaseUnityPlugin)this).Config.Bind<float>("Rejoin", "ConnectWaitSeconds", 12f, "How long to wait for the server to answer before the attempt counts as failed.");
JoinWait = ((BaseUnityPlugin)this).Config.Bind<float>("Rejoin", "JoinWaitSeconds", 15f, "How long to wait for the room to open before the attempt counts as failed.");
PublishMatchState = ((BaseUnityPlugin)this).Config.Bind<bool>("Match", "PublishMatchState", true, "While this player is the room's master, publish the current map id and whether a match is running into the room's custom properties, so anyone who comes back can find the match.");
LoadMatchLevel = ((BaseUnityPlugin)this).Config.Bind<bool>("Match", "LoadMatchLevel", true, "On coming back into a running match, load its map on this client. This is a local load: it does not restart the round for the other players.");
AutoSpawn = ((BaseUnityPlugin)this).Config.Bind<bool>("Match", "AutoSpawn", true, "After the map is loaded, ask the game to create this player instead of waiting for the player to press jump.");
KeepMatchWhenPlayerLeaves = ((BaseUnityPlugin)this).Config.Bind<bool>("Match", "KeepMatchWhenPlayerLeaves", true, "ROUNDS ends the match for everyone when any player leaves the room. With three or more players this stops that, so a player who dropped has something to come back to. A two player room keeps the game's own behaviour: there is no match left without the opponent.");
PanelEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Panel", "Enabled", true, "The small status panel.");
PanelKey = ((BaseUnityPlugin)this).Config.Bind<string>("Panel", "ToggleKey", "F9", "Key that shows and hides the panel.");
ApplyLanModSettings();
try
{
_panelKey = (KeyCode)Enum.Parse(typeof(KeyCode), PanelKey.Value.Trim(), ignoreCase: true);
}
catch
{
Log.LogWarning((object)("[REJOIN] could not parse ToggleKey '" + PanelKey.Value + "', using F9"));
}
int num = Patcher.PatchAll();
Log.LogInfo((object)string.Format("[REJOIN] ROUNDS LAN Rejoin {0} | enabled={1} server={2}:{3} | autoRejoin={4} attempts={5} | patches={6}", "0.1.0", Enabled.Value, Address.Value, Port.Value, AutoRejoin.Value, MaxAttempts.Value, num));
}
private void ApplyLanModSettings()
{
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
if (!ReadLanModConfig.Value)
{
return;
}
try
{
string text = Path.Combine(Paths.ConfigPath, "tiago.rounds.lanphoton.cfg");
if (File.Exists(text))
{
ConfigFile val = new ConfigFile(text, false);
ConfigEntry<string> val2 = val.Bind<string>("Server", "Address", "", "(read from ROUNDS LAN Photon)");
ConfigEntry<int> val3 = val.Bind<int>("Server", "Port", 0, "(read from ROUNDS LAN Photon)");
if (!string.IsNullOrEmpty(val2.Value))
{
Address.Value = val2.Value;
}
if (val3.Value > 0)
{
Port.Value = val3.Value;
}
Log.LogInfo((object)("[REJOIN] server taken from the LAN mod's config: " + Address.Value + ":" + Port.Value));
}
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] could not read the LAN mod's config: " + ex.Message));
}
}
internal static bool OnDisconnectedPrefix(object[] __args)
{
try
{
if (!Enabled.Value)
{
return true;
}
if (_leaveExpected)
{
return true;
}
int disconnectCause = 0;
try
{
if (__args != null && __args.Length != 0 && __args[0] != null)
{
disconnectCause = Convert.ToInt32(__args[0]);
}
}
catch
{
disconnectCause = -1;
}
RejoinAction rejoinAction = RejoinPlan.Next(AutoRejoin.Value, RejoinPlan.IsNetworkDrop(disconnectCause), !string.IsNullOrEmpty(SavedRoom), Attempts, MaxAttempts.Value);
Log.LogInfo((object)("[REJOIN] disconnect (cause " + disconnectCause + ") -> " + rejoinAction.ToString() + " | room '" + (SavedRoom ?? "none") + "' attempts " + Attempts + "/" + MaxAttempts.Value));
if (rejoinAction != RejoinAction.Rejoin)
{
return true;
}
if ((Object)(object)Instance != (Object)null)
{
((MonoBehaviour)Instance).StartCoroutine(Instance.CoRejoin("the connection dropped"));
}
return false;
}
catch (Exception ex)
{
if (Log != null)
{
Log.LogWarning((object)("[REJOIN] disconnect handling failed: " + ex.Message));
}
return true;
}
}
internal static bool OnPlayerLeftRoomPrefix(object[] __args)
{
try
{
if (!Enabled.Value || !KeepMatchWhenPlayerLeaves.Value)
{
return true;
}
Type photonNetwork = Ref.PhotonNetwork;
if (photonNetwork == null)
{
return true;
}
if (Ref.GetStaticBool(photonNetwork, "OfflineMode"))
{
return true;
}
if (Ref.GetStaticBool(photonNetwork, "IsMasterClient"))
{
return true;
}
int num = ((Ref.GetStatic(photonNetwork, "PlayerList") is Array array) ? array.Length : 0);
if (num < 2)
{
return true;
}
bool inMatch;
int num2 = CurrentLevel(out inMatch);
if (!inMatch)
{
return true;
}
Log.LogInfo((object)("[REJOIN] a player left with " + num + " still here on map " + num2 + ": keeping the match alive instead of restarting everyone"));
return false;
}
catch (Exception ex)
{
if (Log != null)
{
Log.LogWarning((object)("[REJOIN] player-left handling failed: " + ex.Message));
}
return true;
}
}
private void Update()
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
if (Enabled == null || !Enabled.Value)
{
return;
}
try
{
if (Input.GetKeyDown(_panelKey))
{
_panelVisible = !_panelVisible;
}
}
catch
{
}
TrackRoom();
Publish();
}
private void TrackRoom()
{
try
{
Type photonNetwork = Ref.PhotonNetwork;
if (photonNetwork == null || !Ref.GetStaticBool(photonNetwork, "InRoom") || Ref.GetStaticBool(photonNetwork, "OfflineMode"))
{
return;
}
string text = Ref.Get(Ref.GetStatic(photonNetwork, "CurrentRoom"), "Name") as string;
if (!string.IsNullOrEmpty(text))
{
if (text != SavedRoom)
{
SavedRoom = text;
Attempts = 0;
_typedRoom = text;
_published = null;
Log.LogInfo((object)("[REJOIN] in room '" + text + "' on " + (Ref.GetStatic(photonNetwork, "ServerAddress") ?? "?")));
}
string text2 = "in room '" + text + "'";
if (!_rejoining && Status != text2)
{
Status = text2;
}
}
}
catch (Exception ex)
{
if (!_warned)
{
_warned = true;
Log.LogWarning((object)("[REJOIN] room tracking failed: " + ex.Message));
}
}
}
private void Publish()
{
if (PublishMatchState == null || !PublishMatchState.Value || Time.realtimeSinceStartup < _nextPublish)
{
return;
}
_nextPublish = Time.realtimeSinceStartup + 1f;
try
{
Type photonNetwork = Ref.PhotonNetwork;
if (photonNetwork == null || !Ref.GetStaticBool(photonNetwork, "InRoom") || !Ref.GetStaticBool(photonNetwork, "IsMasterClient") || Ref.GetStaticBool(photonNetwork, "OfflineMode"))
{
return;
}
bool inMatch;
int levelId = CurrentLevel(out inMatch);
string text = (inMatch ? "match" : "lobby") + ":" + levelId;
if (text == _published)
{
return;
}
object obj = Ref.GetStatic(photonNetwork, "CurrentRoom");
if (obj != null)
{
Hashtable hashtable = MatchSnapshot.ToProperties(inMatch, levelId);
MethodInfo method = obj.GetType().GetMethod("SetCustomProperties");
if (!(method == null))
{
method.Invoke(obj, new object[3] { hashtable, null, null });
_published = text;
Log.LogInfo((object)("[REJOIN] published room state: " + text));
}
}
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] could not publish the match state: " + ex.Message));
}
}
internal IEnumerator CoRejoin(string why)
{
if (_rejoining)
{
Log.LogInfo((object)"[REJOIN] already rejoining, ignoring a second request");
yield break;
}
_rejoining = true;
_dialFailed = false;
Status = "rejoining ...";
try
{
string room = RejoinPlan.RoomToJoin(SavedRoom, _typedRoom);
Log.LogInfo((object)("[REJOIN] " + why + ": going back to '" + room + "' on " + Address.Value + ":" + Port.Value));
yield return (object)new WaitForSecondsRealtime(Mathf.Max(0f, RetryDelay.Value));
yield return CoDial(room);
if (!_dialFailed)
{
if (Ref.PhotonNetwork == null || !Ref.GetStaticBool(Ref.PhotonNetwork, "InRoom"))
{
Fail("the room did not open");
yield break;
}
SavedRoom = room;
Attempts = 0;
Log.LogInfo((object)("[REJOIN] back in '" + room + "'; " + (Ref.GetStaticBool(Ref.PhotonNetwork, "IsMasterClient") ? "this PC is the master" : "the host is the other player")));
yield return CoRestoreMatch(room);
HideLoading();
Status = "back in '" + room + "'";
}
}
finally
{
_rejoining = false;
RestoreGameSettings();
}
}
private IEnumerator CoDial(string room)
{
Type pn = Ref.PhotonNetwork;
if (pn == null)
{
_dialFailed = true;
Fail("PhotonNetwork not found");
yield break;
}
if (!Ref.GetStaticBool(pn, "IsConnectedAndReady"))
{
Ref.SetStatic(pn, "OfflineMode", false);
ApplyLanSettings();
Log.LogInfo((object)("[REJOIN] connecting to " + Address.Value + ":" + Port.Value));
Ref.CallStatic(pn, "ConnectUsingSettings", Type.EmptyTypes, null);
float waited = 0f;
while (!Ref.GetStaticBool(pn, "IsConnectedAndReady") && waited < ConnectWait.Value)
{
waited += Time.unscaledDeltaTime;
yield return null;
}
}
if (!Ref.GetStaticBool(pn, "IsConnectedAndReady"))
{
_dialFailed = true;
Fail("no answer from " + Address.Value + ":" + Port.Value);
yield break;
}
Log.LogInfo((object)"[REJOIN] connected; asking for the room");
object obj = Ref.CallStatic(pn, "RejoinRoom", new Type[1] { typeof(string) }, new object[1] { room });
bool b = default(bool);
int num;
if (obj is bool)
{
b = (bool)obj;
num = 1;
}
else
{
num = 0;
}
bool flag = (byte)((uint)num & (b ? 1u : 0u)) != 0;
if (flag)
{
Log.LogInfo((object)"[REJOIN] RejoinRoom sent");
}
else
{
Log.LogInfo((object)"[REJOIN] RejoinRoom refused; joining the room as a new player");
object obj2 = Ref.CallStatic(pn, "JoinRoom", new Type[2]
{
typeof(string),
typeof(string[])
}, new object[2] { room, null });
bool flag2 = default(bool);
int num2;
if (obj2 is bool)
{
flag2 = (bool)obj2;
num2 = 1;
}
else
{
num2 = 0;
}
flag = (byte)((uint)num2 & (flag2 ? 1u : 0u)) != 0;
}
if (!flag)
{
_dialFailed = true;
Fail("the room call was refused (see the log above)");
yield break;
}
float joined2 = 0f;
while (!Ref.GetStaticBool(pn, "InRoom") && joined2 < JoinWait.Value)
{
joined2 += Time.unscaledDeltaTime;
yield return null;
}
if (!Ref.GetStaticBool(pn, "InRoom"))
{
_dialFailed = true;
Fail("no room after " + JoinWait.Value.ToString("0") + "s");
}
}
private IEnumerator CoRestoreMatch(string room)
{
if (LoadMatchLevel == null || !LoadMatchLevel.Value)
{
yield break;
}
int level = -1;
try
{
IDictionary properties = Ref.Get(Ref.GetStatic(Ref.PhotonNetwork, "CurrentRoom"), "CustomProperties") as IDictionary;
MatchSnapshot matchSnapshot = MatchSnapshot.FromProperties(room, properties);
level = matchSnapshot.LevelId;
Log.LogInfo((object)("[REJOIN] room says: " + (matchSnapshot.InMatch ? "a match is running" : "no match published") + ", map " + (matchSnapshot.HasLevel ? level.ToString() : "unknown")));
if (!matchSnapshot.HasLevel && SavedLevel >= 0)
{
level = SavedLevel;
}
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] could not read the match state: " + ex.Message));
}
if (!RejoinPlan.ShouldLoadLevel(level >= 0))
{
Log.LogInfo((object)"[REJOIN] no map to load: back in the lobby, which is where the game leaves you");
yield break;
}
if (!LoadLevel(level))
{
Log.LogWarning((object)("[REJOIN] the game would not load map " + level + "; the player is in the room but not in the match"));
yield break;
}
float waited = 0f;
while (CurrentLevelId() != level && waited < 10f)
{
waited += Time.unscaledDeltaTime;
yield return null;
}
Log.LogInfo((object)("[REJOIN] map " + level + " is loaded on this client"));
if (AutoSpawn != null && AutoSpawn.Value)
{
if (AlreadyHasPlayer())
{
Log.LogInfo((object)"[REJOIN] this client still has its player: nothing to create");
}
else if (!CreatePlayer())
{
Log.LogWarning((object)"[REJOIN] could not create the player automatically: press jump in the match to join");
Status = "in the match map: press jump to join";
}
else
{
Status = "back in the match";
}
}
}
private void Fail(string why)
{
Attempts++;
Log.LogWarning((object)("[REJOIN] attempt " + Attempts + " failed: " + why));
if (Attempts >= MaxAttempts.Value)
{
Status = "gave up after " + Attempts + " attempt(s): left in the menu";
Log.LogWarning((object)"[REJOIN] giving up; handing the game back to its own error handling");
RestartToMenu();
return;
}
Status = "attempt " + Attempts + " failed (" + why + "), retrying";
if ((Object)(object)Instance != (Object)null)
{
((MonoBehaviour)Instance).StartCoroutine(Instance.CoRetry());
}
}
internal IEnumerator CoRetry()
{
yield return (object)new WaitForSecondsRealtime(Mathf.Max(1f, RetryDelay.Value));
if (!_rejoining && AutoRejoin.Value && !string.IsNullOrEmpty(SavedRoom))
{
yield return CoRejoin("retrying after a failed attempt");
}
}
private static void RestartToMenu()
{
try
{
Type type = Ref.Find("NetworkConnectionHandler");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
MethodInfo methodInfo = ((type == null) ? null : type.GetMethod("NetworkRestart", BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null));
if (obj != null && methodInfo != null)
{
methodInfo.Invoke(obj, null);
}
else if (Ref.PhotonNetwork != null)
{
Ref.CallStatic(Ref.PhotonNetwork, "Disconnect", Type.EmptyTypes, null);
}
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] could not restart the game's networking: " + ex.Message));
}
}
private static int CurrentLevel(out bool inMatch)
{
inMatch = false;
try
{
Type type = Ref.Find("MapManager");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
if (obj == null)
{
return -1;
}
inMatch = Ref.Get(obj, "currentMap") != null;
int num = CurrentLevelId();
if (num >= 0)
{
SavedLevel = num;
}
return num;
}
catch
{
return -1;
}
}
private static int CurrentLevelId()
{
try
{
Type type = Ref.Find("MapManager");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
if (obj == null)
{
return -1;
}
object obj2 = Ref.Get(obj, "currentLevelID");
return (obj2 == null) ? (-1) : Convert.ToInt32(obj2);
}
catch
{
return -1;
}
}
private static bool LoadLevel(int level)
{
try
{
Type type = Ref.Find("MapManager");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
MethodInfo methodInfo = ((type == null) ? null : type.GetMethod("LoadLevelFromID", new Type[3]
{
typeof(int),
typeof(bool),
typeof(bool)
}));
if (obj == null || methodInfo == null)
{
return false;
}
methodInfo.Invoke(obj, new object[3] { level, false, true });
return true;
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] LoadLevelFromID threw: " + ex.Message));
return false;
}
}
private static bool AlreadyHasPlayer()
{
try
{
Type type = Ref.Find("PlayerManager");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
if (!(((obj == null) ? null : Ref.Get(obj, "players")) is IList list))
{
return false;
}
bool flag = default(bool);
foreach (object item in list)
{
object obj2 = Ref.Get(Ref.Get(Ref.Get(item, "data"), "view"), "IsMine");
int num;
if (obj2 is bool)
{
flag = (bool)obj2;
num = 1;
}
else
{
num = 0;
}
if (((uint)num & (flag ? 1u : 0u)) != 0)
{
return true;
}
}
}
catch
{
}
return false;
}
private static bool CreatePlayer()
{
try
{
Type type = Ref.Find("PlayerAssigner");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
if (obj == null)
{
return false;
}
Ref.Set(obj, "hasCreatedLocalPlayer", false);
try
{
MethodInfo method = type.GetMethod("SetPlayersCanJoin", new Type[1] { typeof(bool) });
if (method != null)
{
method.Invoke(obj, new object[1] { true });
}
}
catch
{
}
MethodInfo methodInfo = null;
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo2 in methods)
{
if (methodInfo2.Name == "CreatePlayer")
{
methodInfo = methodInfo2;
break;
}
}
if (methodInfo == null)
{
return false;
}
object[] parameters = ((methodInfo.GetParameters().Length != 2) ? new object[1] : new object[2] { null, false });
if (methodInfo.Invoke(obj, parameters) is IEnumerator enumerator && (Object)(object)Instance != (Object)null)
{
((MonoBehaviour)Instance).StartCoroutine(enumerator);
return true;
}
return false;
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] CreatePlayer threw: " + ex.Message));
return false;
}
}
private static void HideLoading()
{
try
{
Type type = Ref.Find("LoadingScreen");
object obj = ((type == null) ? null : Ref.GetStatic(type, "instance"));
MethodInfo methodInfo = ((type == null) ? null : type.GetMethod("StopLoading", Type.EmptyTypes));
if (obj != null && methodInfo != null)
{
methodInfo.Invoke(obj, null);
}
}
catch
{
}
}
private static void ApplyLanSettings()
{
try
{
Type photonNetwork = Ref.PhotonNetwork;
if (photonNetwork == null)
{
return;
}
object obj = Ref.GetStatic(photonNetwork, "PhotonServerSettings");
object obj2 = ((obj == null) ? null : Ref.Get(obj, "AppSettings"));
if (obj2 == null)
{
Log.LogWarning((object)"[REJOIN] AppSettings not found; the connect may go to the cloud");
return;
}
if (!_captured)
{
_savedServer = Ref.Get(obj2, "Server") as string;
_savedRegion = Ref.Get(obj2, "FixedRegion") as string;
_savedAppId = Ref.Get(obj2, "AppIdRealtime") as string;
object obj3 = Ref.Get(obj2, "Port");
_savedPort = ((obj3 != null) ? Convert.ToInt32(obj3) : 0);
object obj4 = Ref.Get(obj2, "UseNameServer");
bool flag = default(bool);
int num;
if (obj4 is bool)
{
flag = (bool)obj4;
num = 1;
}
else
{
num = 0;
}
_savedUseNameServer = (byte)((uint)num & (flag ? 1u : 0u)) != 0;
_captured = true;
Log.LogInfo((object)("[REJOIN] saved the game's own Photon settings: Server=" + _savedServer + " Port=" + _savedPort + " UseNameServer=" + _savedUseNameServer));
}
Ref.Set(obj2, "Server", Address.Value);
Ref.Set(obj2, "Port", Port.Value);
Ref.Set(obj2, "UseNameServer", false);
Ref.Set(obj2, "FixedRegion", "");
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] could not set the server: " + ex.Message));
}
}
private static void RestoreGameSettings()
{
if (!_captured)
{
return;
}
try
{
Type photonNetwork = Ref.PhotonNetwork;
object obj = ((photonNetwork == null) ? null : Ref.GetStatic(photonNetwork, "PhotonServerSettings"));
object obj2 = ((obj == null) ? null : Ref.Get(obj, "AppSettings"));
if (obj2 != null)
{
Ref.Set(obj2, "Server", _savedServer);
Ref.Set(obj2, "Port", _savedPort);
Ref.Set(obj2, "UseNameServer", _savedUseNameServer);
Ref.Set(obj2, "FixedRegion", _savedRegion ?? "");
if (!string.IsNullOrEmpty(_savedAppId))
{
Ref.Set(obj2, "AppIdRealtime", _savedAppId);
}
Log.LogInfo((object)("[REJOIN] the game's own Photon settings are back (Server=" + _savedServer + " Port=" + _savedPort + ")"));
_captured = false;
}
}
catch (Exception ex)
{
Log.LogWarning((object)("[REJOIN] could not restore the game's settings: " + ex.Message));
}
}
private void OnGUI()
{
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_0092: Unknown result type (might be due to invalid IL or missing references)
if (PanelEnabled == null || !PanelEnabled.Value || !_panelVisible || Enabled == null || !Enabled.Value)
{
return;
}
try
{
Rect val = default(Rect);
((Rect)(ref val))..ctor(12f, (float)Screen.height - 172f, 430f, 160f);
GUI.Box(val, "");
GUILayout.BeginArea(new Rect(((Rect)(ref val)).x + 8f, ((Rect)(ref val)).y + 6f, ((Rect)(ref val)).width - 16f, ((Rect)(ref val)).height - 12f));
GUILayout.Label("REJOIN 0.1.0 (" + PanelKey.Value + " hides this)", Small(), Array.Empty<GUILayoutOption>());
GUILayout.Label("state: " + Status, Small(), Array.Empty<GUILayoutOption>());
GUILayout.Label("room: " + (SavedRoom ?? "none") + " server: " + Address.Value + ":" + Port.Value, Small(), Array.Empty<GUILayoutOption>());
GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
_typedRoom = GUILayout.TextField(_typedRoom ?? "", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(150f) });
if (GUILayout.Button("Rejoin now", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }) && !_rejoining)
{
SavedRoom = RejoinPlan.RoomToJoin(SavedRoom, _typedRoom);
Attempts = 0;
((MonoBehaviour)this).StartCoroutine(CoRejoin("asked from the panel"));
}
if (GUILayout.Button("Join match", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(110f) }) && !_rejoining)
{
SavedRoom = RejoinPlan.RoomToJoin(null, _typedRoom);
Attempts = 0;
((MonoBehaviour)this).StartCoroutine(CoRejoin("joining a running match from the panel"));
}
if (GUILayout.Button("Leave", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(60f) }))
{
_leaveExpected = true;
SavedRoom = null;
Attempts = 0;
RestartToMenu();
Status = "left the room";
((MonoBehaviour)this).StartCoroutine(ClearLeaveFlag());
}
GUILayout.EndHorizontal();
GUILayout.Label(AutoRejoin.Value ? ("a dropped connection is retried " + MaxAttempts.Value + " times by itself") : "automatic rejoin is off: the button above is the only way back", Small(), Array.Empty<GUILayoutOption>());
GUILayout.EndArea();
}
catch (Exception ex)
{
if (!_warned)
{
_warned = true;
Log.LogWarning((object)("[REJOIN] panel draw failed: " + ex.Message));
}
}
}
private static IEnumerator ClearLeaveFlag()
{
yield return (object)new WaitForSecondsRealtime(5f);
_leaveExpected = false;
}
private static GUIStyle Small()
{
//IL_0011: Unknown result type (might be due to invalid IL or missing references)
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Expected O, but got Unknown
if (_small == null)
{
_small = new GUIStyle(GUI.skin.label)
{
fontSize = 11
};
}
return _small;
}
}
internal static class Patcher
{
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.rejoin");
int num = 0;
num += (PatchDisconnect(harmony) ? 1 : 0);
num += (PatchPlayerLeft(harmony) ? 1 : 0);
Plugin.Log.LogInfo((object)("[REJOIN] patched " + num + " game callback(s)"));
return num;
}
private static bool PatchDisconnect(Harmony harmony)
{
//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
//IL_00b3: Expected O, but got Unknown
try
{
Type type = Ref.Find("NetworkConnectionHandler");
if (type == null)
{
Plugin.Log.LogWarning((object)"[REJOIN] NetworkConnectionHandler not found");
return false;
}
MethodInfo methodInfo = null;
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo2 in methods)
{
if (!(methodInfo2.Name != "OnDisconnected") && methodInfo2.GetParameters().Length == 1)
{
methodInfo = methodInfo2;
break;
}
}
if (methodInfo == null)
{
Plugin.Log.LogWarning((object)"[REJOIN] no OnDisconnected to patch");
return false;
}
harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin).GetMethod("OnDisconnectedPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
Plugin.Log.LogInfo((object)("[REJOIN] hooked " + Describe(methodInfo)));
return true;
}
catch (Exception ex)
{
Plugin.Log.LogWarning((object)("[REJOIN] could not hook OnDisconnected: " + ex.Message));
return false;
}
}
private static bool PatchPlayerLeft(Harmony harmony)
{
//IL_0096: Unknown result type (might be due to invalid IL or missing references)
//IL_00a4: Expected O, but got Unknown
try
{
Type type = Ref.Find("NetworkConnectionHandler");
if (type == null)
{
return false;
}
MethodInfo methodInfo = null;
MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo2 in methods)
{
if (!(methodInfo2.Name != "OnPlayerLeftRoom") && methodInfo2.GetParameters().Length == 1)
{
methodInfo = methodInfo2;
break;
}
}
if (methodInfo == null)
{
Plugin.Log.LogWarning((object)"[REJOIN] no OnPlayerLeftRoom to patch");
return false;
}
harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Plugin).GetMethod("OnPlayerLeftRoomPrefix", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
Plugin.Log.LogInfo((object)("[REJOIN] hooked " + Describe(methodInfo)));
return true;
}
catch (Exception ex)
{
Plugin.Log.LogWarning((object)("[REJOIN] could not hook OnPlayerLeftRoom: " + ex.Message));
return false;
}
}
private static string Describe(MethodBase m)
{
return m.DeclaringType.Name + "." + m.Name + "(" + string.Join(", ", (from p in m.GetParameters()
select p.ParameterType.Name).ToArray()) + ")";
}
}
internal static class Ref
{
private static Type _photonNetwork;
private static bool _resolved;
internal static Type PhotonNetwork
{
get
{
if (!_resolved)
{
_resolved = true;
_photonNetwork = Find("Photon.Pun.PhotonNetwork") ?? Find("PhotonNetwork");
Plugin.Log.LogInfo((object)("[REJOIN] PhotonNetwork: " + ((_photonNetwork == null) ? "NOT FOUND" : _photonNetwork.Assembly.GetName().Name)));
}
return _photonNetwork;
}
}
internal static Type Find(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(Type t, string name)
{
return Get(t, name, isStatic: true);
}
internal static bool GetStaticBool(Type t, string name)
{
object obj = Get(t, name, isStatic: true);
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 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)("[REJOIN] could not set " + name + ": " + ex.Message));
}
return false;
}
internal static void SetStatic(Type t, string name, object value)
{
Set(t, name, value, isStatic: true);
}
internal 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 (Exception ex)
{
Plugin.Log.LogWarning((object)("[REJOIN] " + name + " failed: " + ex.Message));
return null;
}
}
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 MatchKeys
{
internal const string InMatch = "rejoin.inmatch";
internal const string LevelId = "rejoin.level";
}
internal sealed class MatchSnapshot
{
internal string RoomName;
internal bool InMatch;
internal int LevelId = -1;
internal bool HasLevel => LevelId >= 0;
internal bool HasMatchState
{
get
{
if (!InMatch)
{
return HasLevel;
}
return true;
}
}
internal static MatchSnapshot ForRoom(string roomName)
{
return new MatchSnapshot
{
RoomName = roomName
};
}
internal static MatchSnapshot FromProperties(string roomName, IDictionary properties)
{
MatchSnapshot matchSnapshot = ForRoom(roomName);
if (properties == null)
{
return matchSnapshot;
}
object obj = Lookup(properties, "rejoin.inmatch");
bool result;
if (obj is bool inMatch)
{
matchSnapshot.InMatch = inMatch;
}
else if (obj != null && bool.TryParse(obj.ToString(), out result))
{
matchSnapshot.InMatch = result;
}
object obj2 = Lookup(properties, "rejoin.level");
int num = -1;
if (obj2 is int num2)
{
num = num2;
}
else if (obj2 is byte b)
{
num = b;
}
else if (obj2 is short num3)
{
num = num3;
}
else if (obj2 != null)
{
num = (int.TryParse(obj2.ToString(), out var result2) ? result2 : (-1));
}
matchSnapshot.LevelId = ((num < 0) ? (-1) : num);
return matchSnapshot;
}
private static object Lookup(IDictionary d, string key)
{
try
{
return d.Contains(key) ? d[key] : null;
}
catch
{
return null;
}
}
internal static Hashtable ToProperties(bool inMatch, int levelId)
{
return new Hashtable
{
["rejoin.inmatch"] = inMatch,
["rejoin.level"] = ((levelId < 0) ? (-1) : levelId)
};
}
}
internal enum RejoinAction
{
None,
Rejoin,
GiveUp
}
internal static class RejoinPlan
{
internal const int CauseNone = 0;
internal const int CauseByClientLogic = 13;
internal static bool IsNetworkDrop(int disconnectCause)
{
if (disconnectCause != 0)
{
return disconnectCause != 13;
}
return false;
}
internal static RejoinAction Next(bool enabled, bool networkDrop, bool haveRoom, int attempts, int maxAttempts)
{
if (!enabled)
{
return RejoinAction.None;
}
if (!networkDrop)
{
return RejoinAction.None;
}
if (!haveRoom)
{
return RejoinAction.None;
}
if (maxAttempts <= 0)
{
return RejoinAction.None;
}
if (attempts >= maxAttempts)
{
return RejoinAction.GiveUp;
}
return RejoinAction.Rejoin;
}
internal static bool ShouldLoadLevel(bool haveLevel)
{
return haveLevel;
}
internal static string RoomToJoin(string saved, string typed)
{
if (!string.IsNullOrEmpty(saved))
{
return saved;
}
if (!string.IsNullOrEmpty(typed))
{
return typed.Trim();
}
return null;
}
}