Decompiled source of TimeAttackCore v0.0.1

plugins/TimeAttackCore.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using CellMenu;
using GTFO.API;
using GTFO.API.JSON;
using Globals;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using SNetwork;
using TMPro;
using TimeAttackCore.API;
using TimeAttackCore.Data;
using TimeAttackCore.LobbySync;
using TimeAttackCore.ServerUpdates;
using TimeAttackCore.UI;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("0.0.1")]
[assembly: AssemblyInformationalVersion("0.0.1")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyVersion("0.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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;
		}
	}
}
internal class ManifestInfo
{
	internal const string TSName = "TimeAttackCore";

	internal const string TSDescription = "This mod is used for GTFO Time Attack.";

	internal const string TSVersion = "0.0.1";

	internal const string TSAuthor = "Tgb03";

	internal const string TSWebsite = "https://github.com/Tgb03/TimeAttackCore";
}
namespace TimeAttackCore
{
	[BepInPlugin("dev.Tgb03.gtfo.TimeAttackCore", "TimeAttackCore", "0.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BasePlugin
	{
		[CompilerGenerated]
		private static class <>O
		{
			public static GameStateChangedDelegate <0>__Initializer;

			public static GameStateChangedDelegate <1>__OnGameStateChanged;
		}

		public const string GUID = "dev.Tgb03.gtfo.TimeAttackCore";

		public const string MOD_NAME = "TimeAttackCore";

		public const string VERSION = "0.0.1";

		internal static ManualLogSource L;

		internal static ApiClient Api;

		private static readonly Harmony _harmony = new Harmony("dev.Tgb03.gtfo.TimeAttackCore");

		private static bool initialized = false;

		public override void Load()
		{
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			L = ((BasePlugin)this).Log;
			TimeAttackConfig.Initialize(((BasePlugin)this).Config);
			Api = new ApiClient(new Uri(TimeAttackConfig.ServerAddress.Value));
			RenderTimerUI.Register();
			_harmony.PatchAll(Assembly.GetExecutingAssembly());
			object obj = <>O.<0>__Initializer;
			if (obj == null)
			{
				GameStateChangedDelegate val = Initializer;
				<>O.<0>__Initializer = val;
				obj = (object)val;
			}
			EventAPI.OnGameStateChanged += (GameStateChangedDelegate)obj;
			object obj2 = <>O.<1>__OnGameStateChanged;
			if (obj2 == null)
			{
				GameStateChangedDelegate val2 = LevelTimer.OnGameStateChanged;
				<>O.<1>__OnGameStateChanged = val2;
				obj2 = (object)val2;
			}
			EventAPI.OnGameStateChanged += (GameStateChangedDelegate)obj2;
			L.LogInfo((object)"Plugin loaded!");
		}

		public static void Initializer(eGameStateName oldState, eGameStateName newState)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Invalid comparison between Unknown and I4
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Invalid comparison between Unknown and I4
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			if ((int)oldState == 2 && (int)newState == 4 && !initialized)
			{
				initialized = true;
				UIPage.Initialize();
				HandlerList.InitializeDefault();
				JoinGame.StartupLoad();
				GameObject val = new GameObject("RenderTimerUI_Host");
				Object.DontDestroyOnLoad((Object)val);
				((Object)val).hideFlags = (HideFlags)61;
				val.AddComponent<RenderTimerUI>();
				TimeAttackCore.LobbySync.LobbySync.Initialize();
			}
		}
	}
}
namespace TimeAttackCore.UI
{
	internal class JoinGame
	{
		public static string GameName = "";

		public static string Password = "";

		private static List<GameObject> spawnedObjects = new List<GameObject>();

		public static void StartupLoad()
		{
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_0127: Unknown result type (might be due to invalid IL or missing references)
			Transform val = GameObject.Find("MainMenuLayer").transform.FindChild("CM_PageLoadout_CellUI(Clone)").FindChild("MovingContent").FindChild("ShareServerId");
			GameObject val2 = Object.Instantiate<GameObject>(((Component)val.FindChild("ShareText")).gameObject);
			TMP_Localizer component = val2.GetComponent<TMP_Localizer>();
			GameObject val3 = Object.Instantiate<GameObject>(((Component)val.FindChild("Button Copy Clipboard")).gameObject);
			TMP_Localizer component2 = val3.GetComponent<TMP_Localizer>();
			Object.Destroy((Object)(object)component);
			Object.Destroy((Object)(object)component2);
			val2.transform.SetParent(val, false);
			val3.transform.SetParent(val, false);
			TextMeshPro component3 = val2.GetComponent<TextMeshPro>();
			((TMP_Text)component3).text = "<size=28>GTFO Time Attack:</size>";
			Transform transform = component3.transform;
			transform.position -= new Vector3(0f, 300f, 0f);
			CM_Item component4 = val3.GetComponent<CM_Item>();
			component4.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)OnBtnPressCallback);
			((TMP_Text)((Il2CppArrayBase<TextMeshPro>)(object)component4.m_texts)[0]).text = "Join with code";
			Transform transform2 = ((Component)component4).transform;
			transform2.position -= new Vector3(0f, 200f, 0f);
			spawnedObjects.Add(val2);
			spawnedObjects.Add(val3);
		}

		public static void SetVisible(bool visible)
		{
			foreach (GameObject spawnedObject in spawnedObjects)
			{
				spawnedObject.SetActive(visible);
			}
		}

		private static async Task JoinGameAsync(string username, string password, string gameName)
		{
			await Plugin.Api.JoinAsync(username, password, gameName, HandlerList.Handle);
			await Task.Delay(500);
			OnJoinFinish();
		}

		private static void OnBtnPressCallback(int value)
		{
			if (!SNet.IsMaster)
			{
				SetVisible(visible: false);
				return;
			}
			string nickName = SNet.LocalPlayer.NickName;
			string empty = string.Empty;
			string empty2 = string.Empty;
			if (TimeAttackConfig.GameName.Value != "" && TimeAttackConfig.GamePassword.Value != "")
			{
				empty = TimeAttackConfig.GameName.Value;
				empty2 = TimeAttackConfig.GamePassword.Value;
			}
			else
			{
				string systemCopyBuffer = GUIUtility.systemCopyBuffer;
				int num = systemCopyBuffer.IndexOf('/');
				empty = systemCopyBuffer.Substring(0, num);
				empty2 = systemCopyBuffer.Substring(num + 1);
			}
			JoinGameAsync(nickName, empty2, empty);
		}

		public static void OnJoinFinish()
		{
			SetVisible(!ApiClient.GetIsConnected());
		}
	}
	internal class RenderLeaderboardUI
	{
		private static List<(string, TextMeshProUGUI)> textMeshes = new List<(string, TextMeshProUGUI)>();

		private static HashSet<string> generated = new HashSet<string>();

		public static List<(string, TextMeshProUGUI)> GenerateRound()
		{
			//IL_0054: 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)
			if (generated.Contains("ROUND"))
			{
				return textMeshes;
			}
			generated.Add("ROUND");
			textMeshes.Add(("ROUND", UIPage.Instance.AddText(UIPage.Instance.GetPanel(), "LeaderboardRoundUI", "", new Vector2(0f, 0f), new Vector2(2510f, 720f), Color.white, 28, (TextAlignmentOptions)257)));
			return textMeshes;
		}
	}
	internal class RenderTimerUI : MonoBehaviour
	{
		private static List<TextMeshProUGUI> textMeshes;

		private static long unixTimestampTo;

		private static long nextUnixTimestampTo;

		private static bool inRound;

		public RenderTimerUI()
		{
		}

		public RenderTimerUI(IntPtr ptr)
			: base(ptr)
		{
		}

		public static void Register()
		{
			ClassInjector.RegisterTypeInIl2Cpp<RenderTimerUI>();
		}

		public static void SetUnixTarget(long target, bool inRound, long nextTarget = 0L)
		{
			unixTimestampTo = target;
			nextUnixTimestampTo = nextTarget;
			RenderTimerUI.inRound = inRound;
		}

		public static List<TextMeshProUGUI> GenerateTimer()
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			if (textMeshes != null)
			{
				return textMeshes;
			}
			textMeshes = new List<TextMeshProUGUI>();
			textMeshes.Add(UIPage.Instance.AddText(UIPage.Instance.GetPanel(), "Timer", "", new Vector2(0f, 0f), new Vector2(2510f, 870f), Color.yellow, 48, (TextAlignmentOptions)257));
			return textMeshes;
		}

		private void Start()
		{
			GenerateTimer();
		}

		private void Update()
		{
			long num = unixTimestampTo - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
			if (num < 0)
			{
				if (inRound || nextUnixTimestampTo <= DateTimeOffset.UtcNow.ToUnixTimeMilliseconds())
				{
					return;
				}
				SetUnixTarget(nextUnixTimestampTo, inRound: true, 0L);
				num = unixTimestampTo - DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
			}
			long value = num / 1000 % 60;
			long value2 = num / 60000 % 60;
			long num2 = num / 3600000;
			string text = ((num2 <= 0) ? $"{value2:D2}:{value:D2}" : $"{num2:D2}:{value2:D2}:{value:D2}");
			string text2 = text;
			text = ((!inRound) ? ("Starting in: " + text2) : text2);
			string text3 = text;
			foreach (TextMeshProUGUI textMesh in textMeshes)
			{
				((TMP_Text)textMesh).SetText(text3, true);
			}
		}
	}
	internal class UIPage
	{
		public static UIPage Instance;

		public const string CANVAS_OBJ_IDENTIFIER = "TimeAttackCoreUICanvas";

		public Dictionary<string, GameObject> spawnedItems = new Dictionary<string, GameObject>();

		private GameObject canvasObject;

		private GameObject panelObject;

		private TMP_FontAsset font;

		public static void Initialize()
		{
			Instance = new UIPage();
			Instance.font = ((TMP_Text)((Il2CppArrayBase<TextMeshPro>)(object)MainMenuGuiLayer.Current.PageLoadout.m_discordButton.m_texts)[0]).font;
		}

		public UIPage()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Expected O, but got Unknown
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			canvasObject = new GameObject("TimeAttackCoreUICanvas");
			Object.DontDestroyOnLoad((Object)(object)canvasObject);
			((Object)canvasObject).hideFlags = (HideFlags)61;
			canvasObject.AddComponent<Canvas>().renderMode = (RenderMode)0;
			canvasObject.AddComponent<GraphicRaycaster>();
			CanvasScaler obj = canvasObject.AddComponent<CanvasScaler>();
			obj.uiScaleMode = (ScaleMode)1;
			obj.referenceResolution = new Vector2(2560f, 1440f);
			obj.screenMatchMode = (ScreenMatchMode)0;
			obj.matchWidthOrHeight = 0.5f;
			panelObject = new GameObject("Panel");
			RectTransform obj2 = panelObject.AddComponent<RectTransform>();
			obj2.sizeDelta = new Vector2(2560f, 1440f);
			((Transform)obj2).SetParent(canvasObject.transform, false);
		}

		public GameObject GetPanel()
		{
			return panelObject;
		}

		public TextMeshProUGUI AddText(GameObject parent, string name, string text, Vector2 position, Vector2 size, Color color, int fontSize = 20, TextAlignmentOptions alignment = (TextAlignmentOptions)514, Color? backgroundColor = null)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: 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)
			GameObject val = new GameObject("TextElement");
			TextMeshProUGUI obj = val.AddComponent<TextMeshProUGUI>();
			((TMP_Text)obj).text = text;
			((TMP_Text)obj).font = Instance.font;
			((TMP_Text)obj).fontSize = fontSize;
			((TMP_Text)obj).m_fontSizeMin = fontSize;
			((TMP_Text)obj).m_maxFontSize = fontSize;
			((TMP_Text)obj).alignment = alignment;
			((Graphic)obj).color = color;
			RectTransform component = val.GetComponent<RectTransform>();
			component.sizeDelta = size;
			component.anchoredPosition = position;
			if (backgroundColor.HasValue)
			{
				GameObject val2 = new GameObject("Background");
				((Graphic)val2.AddComponent<Image>()).color = backgroundColor.Value;
				RectTransform obj2 = val2.AddComponent<RectTransform>();
				obj2.anchoredPosition = position;
				obj2.sizeDelta = size;
				((Transform)obj2).SetParent(parent.transform, false);
				((Transform)component).SetParent(val2.transform, false);
			}
			else
			{
				((Transform)component).SetParent(parent.transform, false);
			}
			spawnedItems.Add(name, val);
			return obj;
		}
	}
}
namespace TimeAttackCore.ServerUpdates
{
	internal enum Result
	{
		Continue,
		Exit
	}
	internal interface IHandler
	{
		Result Handle(string data);
	}
	public class HandlerList
	{
		private static List<IHandler> handlers = new List<IHandler>();

		private static JsonSerializerOptions defaultOptions = new JsonSerializerOptions
		{
			IncludeFields = true
		};

		public static void InitializeDefault()
		{
			handlers.Add(new LogRequest());
			handlers.Add(new LeaderboardHandle());
			handlers.Add(new RoundPhaseHandle());
			defaultOptions.Converters.Add(new ReceiveMessageConverter());
			defaultOptions.Converters.Add(new RoundPhaseConverter());
		}

		public static void Handle(string data)
		{
			using List<IHandler>.Enumerator enumerator = handlers.GetEnumerator();
			while (enumerator.MoveNext() && enumerator.Current.Handle(data) != Result.Exit)
			{
			}
		}

		public static E? DeserializeInto<T, E>(string data)
		{
			return DeserializeInto<T, E>(data, defaultOptions);
		}

		public static E? DeserializeInto<T, E>(string data, JsonSerializerOptions options)
		{
			T val = JsonSerializer.Deserialize<T>(data, options);
			if (val == null)
			{
				return default(E);
			}
			if (!(val is E result))
			{
				return default(E);
			}
			return result;
		}

		public static T? Deserialize<T>(string data)
		{
			return Deserialize<T>(data, defaultOptions);
		}

		public static T? Deserialize<T>(string data, JsonSerializerOptions options)
		{
			return JsonSerializer.Deserialize<T>(data, options);
		}
	}
	internal class LeaderboardHandle : IHandler
	{
		private List<(string, TextMeshProUGUI)> textMeshes = new List<(string, TextMeshProUGUI)>();

		public LeaderboardHandle()
		{
			textMeshes = RenderLeaderboardUI.GenerateRound();
		}

		public Result Handle(string data)
		{
			LeaderboardRender leaderboardRender = HandlerList.DeserializeInto<ReceiveMessage, LeaderboardRender>(data);
			if (leaderboardRender == null)
			{
				return Result.Continue;
			}
			RenderLeaderboard(leaderboardRender);
			TimeAttackCore.LobbySync.LobbySync.SendLeaderboardRender(leaderboardRender);
			return Result.Exit;
		}

		internal void RenderLeaderboard(LeaderboardRender render)
		{
			if (textMeshes == null)
			{
				return;
			}
			string text = "ROUND LEADERBOARD:\n";
			int maxSizeName = GetMaxSizeName(render);
			foreach (LeaderboardRenderEntry entry in render.entries)
			{
				text += ConvertEntry(entry, maxSizeName, render.tag);
			}
			foreach (var (text2, val) in textMeshes)
			{
				if (text2 == render.tag)
				{
					((TMP_Text)val).SetText(text, true);
				}
			}
		}

		private static int GetMaxSizeName(LeaderboardRender render)
		{
			int num = 0;
			foreach (LeaderboardRenderEntry entry in render.entries)
			{
				num = Math.Max(num, entry.name.Length);
			}
			return num;
		}

		private static string ConvertEntry(LeaderboardRenderEntry entry, int nameSize, string tag)
		{
			if (!(tag == "ROUND"))
			{
				return $"{entry.position + 1:D2} {entry.name.PadRight(nameSize)} {entry.points}\n";
			}
			return $"{entry.position + 1:D2} {entry.name.PadRight(nameSize)} {ConvertPointsToTime(entry.points)}\n";
		}

		private static string ConvertPointsToTime(int milliseconds)
		{
			if (milliseconds == int.MinValue)
			{
				return "SECRET";
			}
			int value = milliseconds / 1000 % 60;
			int value2 = milliseconds / 60000 % 60;
			return $"{value2:D2}:{value:D2}";
		}
	}
	internal class LogRequest : IHandler
	{
		public Result Handle(string data)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			ManualLogSource l = Plugin.L;
			bool flag = default(bool);
			BepInExMessageLogInterpolatedStringHandler val = new BepInExMessageLogInterpolatedStringHandler(10, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("received: ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(data);
			}
			l.LogMessage(val);
			return Result.Continue;
		}
	}
	internal class RoundPhaseHandle : IHandler
	{
		private bool was_in_intermission;

		public Result Handle(string data)
		{
			RoundPhase roundPhase = HandlerList.DeserializeInto<ReceiveMessage, RoundPhase>(data);
			if (roundPhase == null)
			{
				return Result.Continue;
			}
			if (!(roundPhase is Lobby))
			{
				if (!(roundPhase is Intermission intermission))
				{
					if (!(roundPhase is Running running))
					{
						if (roundPhase is Finished)
						{
							was_in_intermission = false;
						}
					}
					else
					{
						TimeAttackCore.LobbySync.LobbySync.SendTimer(running.ends_at_ms, in_round: true, 0L);
						RenderTimerUI.SetUnixTarget(running.ends_at_ms, inRound: true, 0L);
						if (running.level.HasValue)
						{
							SetExpedition(running.level.Value);
							if (was_in_intermission)
							{
								StartGame(running.level.Value);
							}
							was_in_intermission = false;
						}
					}
				}
				else if (intermission.level.HasValue)
				{
					if (intermission.starts_at_ms.HasValue)
					{
						long value = intermission.starts_at_ms.Value;
						long num = ((!intermission.end_at_ms.HasValue) ? 0 : intermission.end_at_ms.Value);
						long num2 = num;
						TimeAttackCore.LobbySync.LobbySync.SendTimer(value, in_round: false, num2);
						RenderTimerUI.SetUnixTarget(value, inRound: false, num2);
					}
					SetExpedition(intermission.level.Value);
					was_in_intermission = true;
				}
			}
			else
			{
				was_in_intermission = false;
			}
			return Result.Exit;
		}

		private static void SetExpedition(ExpeditionData data)
		{
			if (SNet.IsInLobby)
			{
				_ = SNet.IsMaster;
			}
		}

		private static void StartGame(ExpeditionData data)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Invalid comparison between Unknown and I4
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Expected O, but got Unknown
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			if (!SNet.IsInLobby || !SNet.IsMaster)
			{
				return;
			}
			pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData();
			bool flag = default(bool);
			if (Global.RundownIdToLoad != data.rundown_id)
			{
				ManualLogSource l = Plugin.L;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(63, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Rejected StartGame because RundownID ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(Global.RundownIdToLoad);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does not match expected: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<uint>(data.rundown_id);
				}
				l.LogError(val);
			}
			else if ((int)activeExpeditionData.tier != data.tier)
			{
				ManualLogSource l2 = Plugin.L;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(58, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Rejected StartGame because tier ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eRundownTier>(activeExpeditionData.tier);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does not match expected: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eRundownTier>((eRundownTier)data.tier);
				}
				l2.LogError(val);
			}
			else if (activeExpeditionData.expeditionIndex != data.index)
			{
				ManualLogSource l3 = Plugin.L;
				BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(59, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Rejected StartGame because index ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(activeExpeditionData.expeditionIndex);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" does not match expected: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<byte>(data.index);
				}
				l3.LogError(val);
			}
			else if (data.seed != 0)
			{
				activeExpeditionData.sessionSeed = data.seed;
			}
		}
	}
}
namespace TimeAttackCore.LobbySync
{
	internal class LobbySync
	{
		protected struct TimerStruct
		{
			public long unix;

			public long nextUnix;

			public bool in_round;
		}

		private static bool initialized;

		private static LeaderboardHandle leaderboardHandler;

		public static void Initialize()
		{
			if (!initialized)
			{
				initialized = true;
				leaderboardHandler = new LeaderboardHandle();
				NetworkAPI.RegisterFreeSizedEvent("LeaderboardRender", (Action<ulong, byte[]>)delegate(ulong id, byte[] leaderboard)
				{
					leaderboardHandler.RenderLeaderboard(LeaderboardRender.Deserialize(leaderboard));
				});
				NetworkAPI.RegisterEvent<TimerStruct>("TIMER", (Action<ulong, TimerStruct>)delegate(ulong id, TimerStruct data)
				{
					RenderTimerUI.SetUnixTarget(data.unix, data.in_round, data.nextUnix);
				});
			}
		}

		public static List<SNet_Player> GetPlayers()
		{
			List<SNet_Player> list = new List<SNet_Player>();
			Enumerator<SNet_Player> enumerator = SNet.Lobby.Players.GetEnumerator();
			while (enumerator.MoveNext())
			{
				SNet_Player current = enumerator.Current;
				if ((Object)(object)current != (Object)(object)SNet.LocalPlayer)
				{
					list.Add(current);
				}
			}
			return list;
		}

		public static void SendLeaderboardRender(LeaderboardRender render)
		{
			if (SNet.IsInLobby && SNet.IsMaster)
			{
				byte[] array = render.Serialize();
				NetworkAPI.InvokeFreeSizedEvent("LeaderboardRender", array, (IEnumerable<SNet_Player>)GetPlayers(), (SNet_ChannelType)2);
			}
		}

		public static void SendTimer(long unix, bool in_round, long nextUnix = 0L)
		{
			if (SNet.IsInLobby && SNet.IsMaster)
			{
				NetworkAPI.InvokeEvent<TimerStruct>("TIMER", new TimerStruct
				{
					unix = unix,
					in_round = in_round,
					nextUnix = nextUnix
				}, GetPlayers(), (SNet_ChannelType)2);
			}
		}
	}
}
namespace TimeAttackCore.Data
{
	internal class GameState
	{
		private static bool IsInGame;

		private static bool IsInRound;
	}
	[Serializable]
	internal class LeaderboardRender : ReceiveMessage
	{
		public List<LeaderboardRenderEntry> entries;

		public string tag;

		public byte[] Serialize()
		{
			List<byte> list = new List<byte>();
			list.AddRange(BitConverter.GetBytes(entries.Count));
			foreach (LeaderboardRenderEntry entry in entries)
			{
				byte[] bytes = Encoding.UTF8.GetBytes(entry.name);
				list.AddRange(BitConverter.GetBytes(bytes.Length));
				list.AddRange(bytes);
				list.AddRange(BitConverter.GetBytes(entry.position));
				list.AddRange(BitConverter.GetBytes(entry.points));
			}
			byte[] bytes2 = Encoding.UTF8.GetBytes(tag);
			list.AddRange(BitConverter.GetBytes(bytes2.Length));
			list.AddRange(bytes2);
			return list.ToArray();
		}

		public static LeaderboardRender Deserialize(byte[] data)
		{
			int offset = 0;
			int num = BitConverter.ToInt32(data, offset);
			offset += 4;
			List<LeaderboardRenderEntry> list = new List<LeaderboardRenderEntry>(num);
			for (int i = 0; i < num; i++)
			{
				string name = ReadString();
				ulong position = (ulong)BitConverter.ToInt64(data, offset);
				offset += 8;
				int points = BitConverter.ToInt32(data, offset);
				offset += 4;
				list.Add(new LeaderboardRenderEntry
				{
					name = name,
					position = position,
					points = points
				});
			}
			string text = ReadString();
			return new LeaderboardRender
			{
				entries = list,
				tag = text
			};
			string ReadString()
			{
				int num2 = BitConverter.ToInt32(data, offset);
				offset += 4;
				string result = Encoding.UTF8.GetString(data, offset, num2);
				offset += num2;
				return result;
			}
		}
	}
	[Serializable]
	internal class LeaderboardRenderEntry
	{
		public string name;

		public ulong position;

		public int points;
	}
	internal class LevelTimer
	{
		public static LevelTimer Instance;

		private DateTime startStamp;

		public LevelTimer()
		{
			startStamp = DateTime.Now;
		}

		public uint GetDuration()
		{
			return (uint)(DateTime.Now - startStamp).TotalMilliseconds;
		}

		public static void OnGameStateChanged(eGameStateName oldState, eGameStateName newState)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Invalid comparison between Unknown and I4
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Invalid comparison between Unknown and I4
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Invalid comparison between Unknown and I4
			if ((int)oldState == 9 && (int)newState == 10)
			{
				Instance = new LevelTimer();
				ApiClient.ApiInstance.SendAsync(BuildRunStarted());
			}
			if ((int)oldState == 10 && (int)newState != 10 && Instance != null)
			{
				uint duration = Instance.GetDuration();
				Instance = null;
				LevelEndResult levelEndResult = (((int)newState == 14) ? LevelEndResult.Win : (((int)newState != 15) ? LevelEndResult.Retired : LevelEndResult.Wiped));
				LevelEndResult result = levelEndResult;
				RunCompleted payload = new RunCompleted
				{
					milliseconds = duration,
					result = result
				};
				ApiClient.ApiInstance.SendAsync(payload);
			}
		}

		private static RunStarted BuildRunStarted()
		{
			RunStarted result = default(RunStarted);
			Enumerator<SNet_Player> enumerator = SNet.LobbyPlayers.GetEnumerator();
			while (enumerator.MoveNext())
			{
				_ = enumerator.Current;
			}
			return result;
		}
	}
	[Serializable]
	internal abstract class ReceiveMessage
	{
	}
	internal sealed class ReceiveMessageConverter : JsonConverter<ReceiveMessage>
	{
		public override ReceiveMessage? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
			JsonElement rootElement = jsonDocument.RootElement;
			if (!rootElement.TryGetProperty("type", out var value))
			{
				throw new JsonException("Missing 'type' property");
			}
			if (!rootElement.TryGetProperty("data", out var value2))
			{
				throw new JsonException("Missing 'data' property");
			}
			string rawText = value2.GetRawText();
			string text = value.GetString();
			if (!(text == "RoundPhase"))
			{
				if (text == "Leaderboard")
				{
					return JsonSerializer.Deserialize<LeaderboardRender>(rawText, options);
				}
				throw new JsonException("Unknown type: " + text);
			}
			return JsonSerializer.Deserialize<RoundPhase>(rawText, options);
		}

		public override void Write(Utf8JsonWriter writer, ReceiveMessage value, JsonSerializerOptions options)
		{
			throw new NotSupportedException();
		}
	}
	internal abstract class RoundPhase : ReceiveMessage
	{
	}
	internal sealed class Lobby : RoundPhase
	{
	}
	internal sealed class Intermission : RoundPhase
	{
		public int next_round;

		public long? starts_at_ms;

		public long? end_at_ms;

		public ExpeditionData? level;
	}
	internal sealed class Running : RoundPhase
	{
		public int round;

		public long started_at_ms;

		public long ends_at_ms;

		public ExpeditionData? level;
	}
	internal sealed class Finished : RoundPhase
	{
	}
	internal sealed class RoundPhaseConverter : JsonConverter<RoundPhase>
	{
		public override RoundPhase? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
			JsonElement rootElement = jsonDocument.RootElement;
			if (!rootElement.TryGetProperty("phase", out var value))
			{
				throw new JsonException("Missing 'phase' property");
			}
			string rawText = rootElement.GetRawText();
			string text = value.GetString();
			return text switch
			{
				"lobby" => new Lobby(), 
				"intermission" => JsonSerializer.Deserialize<Intermission>(rawText, options), 
				"running" => JsonSerializer.Deserialize<Running>(rawText, options), 
				"finished" => new Finished(), 
				_ => throw new JsonException("Unknown phase: " + text), 
			};
		}

		public override void Write(Utf8JsonWriter writer, RoundPhase value, JsonSerializerOptions options)
		{
			throw new NotSupportedException();
		}
	}
	internal class TimeAttackConfig
	{
		public static ConfigEntry<string> ServerAddress { get; private set; }

		public static ConfigEntry<string> GameName { get; private set; }

		public static ConfigEntry<string> GamePassword { get; private set; }

		internal static void Initialize(ConfigFile cfg)
		{
			ServerAddress = cfg.Bind<string>("General", "ServerAddress", "", "Address of the server used to host the games");
			GameName = cfg.Bind<string>("General", "GameName", "", "Name of the game you are going to join. Empty means no automatic joining.");
			GamePassword = cfg.Bind<string>("General", "GamePassword", "", "Password of the game you are going to join. Empty means no automatic joining.");
		}
	}
	[Serializable]
	public enum SessionType
	{
		Admin,
		Caster,
		Player
	}
	[Serializable]
	public struct ConnectRequest
	{
		public string username { get; set; }

		public string password { get; set; }

		public string game_name { get; set; }

		public SessionType session_type { get; set; }
	}
	[Serializable]
	public struct ConnectResponse
	{
		public string token { get; set; }
	}
	[Serializable]
	public enum LevelEndResult
	{
		Wiped,
		Retired,
		Win
	}
	[Serializable]
	public struct RunCompleted
	{
		public ulong milliseconds;

		public LevelEndResult result;
	}
	[Serializable]
	public struct RunStarted
	{
		public List<PlayerData> player_datas;
	}
	[Serializable]
	public struct PlayerData
	{
		public string name;

		public string[] loadout;
	}
	[Serializable]
	public struct ExpeditionData
	{
		public uint rundown_id;

		public byte tier;

		public byte index;

		public int seed;
	}
}
namespace TimeAttackCore.API
{
	internal class ApiClient
	{
		public static ApiConnection ApiInstance = null;

		private static HttpClient client = new HttpClient();

		private readonly Uri _baseUri;

		public ApiClient(Uri baseUri)
		{
			_baseUri = baseUri;
		}

		public static bool GetIsConnected()
		{
			return ApiInstance != null;
		}

		private async Task<string> ConnectAsync(string username, string password, string gameName)
		{
			string content = JsonSerializer.Serialize((object)new ConnectRequest
			{
				username = username,
				password = password,
				game_name = gameName,
				session_type = SessionType.Player
			}, (JsonSerializerOptions)null);
			using StringContent content2 = new StringContent(content, Encoding.UTF8, "application/json");
			using HttpResponseMessage res = await client.PostAsync(new Uri(_baseUri, "/join"), content2);
			switch (res.StatusCode)
			{
			case HttpStatusCode.Conflict:
				throw new Exception("Account of the same name is connected already");
			case HttpStatusCode.NotFound:
				throw new Exception("Game not found");
			case HttpStatusCode.Unauthorized:
				throw new Exception("Wrong password");
			default:
				if (!res.IsSuccessStatusCode)
				{
					throw new Exception("Connect failed: HTTP " + (int)res.StatusCode);
				}
				return JsonSerializer.Deserialize<ConnectResponse>(await res.Content.ReadAsStringAsync(), (JsonSerializerOptions)null).token;
			}
		}

		private async Task<ApiConnection> OpenSocketAsync(string token, Action<string> onMessage, Action onClose, CancellationToken ct = default(CancellationToken))
		{
			UriBuilder uriBuilder = new UriBuilder(_baseUri)
			{
				Scheme = ((_baseUri.Scheme == "https") ? "wss" : "ws"),
				Path = "/ws",
				Query = "token=" + Uri.EscapeDataString(token)
			};
			ClientWebSocket socket = new ClientWebSocket();
			await socket.ConnectAsync(uriBuilder.Uri, ct);
			Task.Run(() => ReceiveLoop(socket, onMessage, onClose, ct), ct);
			return new ApiConnection(socket);
		}

		private static async Task ReceiveLoop(ClientWebSocket socket, Action<string> onMessage, Action onClose, CancellationToken ct)
		{
			byte[] buffer = new byte[8192];
			try
			{
				while (socket.State == WebSocketState.Open && !ct.IsCancellationRequested)
				{
					StringBuilder sb = new StringBuilder();
					WebSocketReceiveResult webSocketReceiveResult;
					do
					{
						webSocketReceiveResult = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
						if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close)
						{
							await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
							return;
						}
						sb.Append(Encoding.UTF8.GetString(buffer, 0, webSocketReceiveResult.Count));
					}
					while (!webSocketReceiveResult.EndOfMessage);
					onMessage(sb.ToString());
				}
			}
			catch (Exception ex)
			{
				Plugin.L.LogError((object)ex);
			}
			finally
			{
				onClose?.Invoke();
			}
		}

		public async Task<ApiConnection> JoinAsync(string username, string password, string gameName, Action<string> onMessage)
		{
			ApiInstance = await OpenSocketAsync(await ConnectAsync(username, password, gameName), onMessage, delegate
			{
				JoinGame.OnJoinFinish();
				ApiInstance = null;
				Console.WriteLine("Disconnected.");
			});
			return ApiInstance;
		}
	}
	internal sealed class ApiConnection : IDisposable
	{
		private readonly ClientWebSocket _socket;

		private readonly JsonSerializerOptions serializerOptions = new JsonSerializerOptions
		{
			IncludeFields = true,
			WriteIndented = false,
			Converters = { (JsonConverter)new JsonStringEnumConverter() }
		};

		private readonly SemaphoreSlim _sendLock = new SemaphoreSlim(1, 1);

		public bool IsOpen => _socket.State == WebSocketState.Open;

		public ApiConnection(ClientWebSocket socket)
		{
			_socket = socket;
		}

		public async Task SendAsync(string message, CancellationToken ct = default(CancellationToken))
		{
			if (!IsOpen)
			{
				throw new InvalidOperationException("WebSocket is not open");
			}
			byte[] bytes = Encoding.UTF8.GetBytes(message);
			await _sendLock.WaitAsync(ct);
			try
			{
				await _socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, endOfMessage: true, ct);
			}
			finally
			{
				_sendLock.Release();
			}
		}

		public Task SendAsync<T>(T payload, CancellationToken ct = default(CancellationToken))
		{
			return SendAsync(JsonSerializer.Serialize((object)payload, serializerOptions), ct);
		}

		public async Task CloseAsync()
		{
			if (_socket.State == WebSocketState.Open)
			{
				await _sendLock.WaitAsync();
				try
				{
					await _socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
				}
				finally
				{
					_sendLock.Release();
				}
			}
		}

		public void Dispose()
		{
			_sendLock.Dispose();
			_socket.Dispose();
		}
	}
}