Decompiled source of SpeedRunCU v1.0.2

SpeedrunCU.dll

Decompiled an hour ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Newtonsoft.Json.Linq;
using UnityEngine;
using UnityEngine.Networking;

[assembly: AssemblyMetadata("Notice", "Copyright (c) casualexpie. All rights reserved. Do NOT decompile, disassemble, or reverse-engineer this assembly. Report bug symptoms on the Nexus Bugs page; do not post decompiled or reconstructed source. Reverse-engineering this DLL is not authorized.")]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace SpeedrunCU;

[BepInPlugin("speedruncu", "Speedrun CU", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	public const string Version = "1.0.0";

	public const string BaseUrl = "https://speedrun.smellypawz.com";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	internal static ConfigEntry<bool> ShowTimer;

	internal static ConfigEntry<bool> ShowSplits;

	internal static ConfigEntry<KeyCode> BoardKey;

	internal static ConfigEntry<int> TimerCorner;

	private void Awake()
	{
		//IL_0098: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Expected O, but got Unknown
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b7: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		ShowTimer = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowTimer", true, "Show the run timer in the top-right corner during a run.");
		ShowSplits = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowSplits", true, "Show the time you reached each layer under the timer.");
		BoardKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Keys", "Leaderboard", (KeyCode)289, "Opens the leaderboard window.");
		TimerCorner = ((BaseUnityPlugin)this).Config.Bind<int>("Display", "TimerCorner", 0, new ConfigDescription("Where the timer sits. 0 top right, 1 top left, 2 bottom right, 3 bottom left.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 3), new object[0]));
		Account.Load();
		Harmony h = new Harmony("speedruncu");
		int num = 0;
		num += Hook(h, typeof(PreRunScript), "StartRun", null, "StartRunPostfix");
		num += Hook(h, typeof(WorldGeneration), "Start", null, "WorldStartPostfix");
		num += Hook(h, typeof(WorldGeneration), "EscapeEnding", "EscapePrefix", null);
		num += Hook(h, typeof(WorldGeneration), "BiopodEnding", "BiopodPrefix", null);
		num += Hook(h, typeof(WorldGeneration), "BiopodEndingAlt", "BiopodPrefix", null);
		num += Hook(h, typeof(WorldGeneration), "BiopodEndingAlt2", "BiopodPrefix", null);
		num += Hook(h, typeof(WorldGeneration), "MercEnding", "MercPrefix", null);
		num += Hook(h, typeof(ConsoleScript), "CheckForCheats", "ConsolePrefix", null);
		Log.LogInfo((object)("Speedrun CU 1.0.0 loaded (" + num + "/8 hooks)."));
		if (num < 8)
		{
			Run.BrokenHooks = true;
		}
	}

	private static int Hook(Harmony h, Type t, string method, string prefix, string postfix)
	{
		//IL_004e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			MethodInfo methodInfo = AccessTools.Method(t, method, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogWarning((object)("Missing game method " + t.Name + "." + method));
				return 0;
			}
			h.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Plugin), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(Plugin), postfix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return 1;
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Couldn't hook " + t.Name + "." + method + ": " + ex.Message));
			return 0;
		}
	}

	private static void StartRunPostfix(PreRunScript __instance)
	{
		try
		{
			FieldInfo fieldInfo = AccessTools.Field(typeof(PreRunScript), "startedLoading");
			if (fieldInfo != null && (bool)fieldInfo.GetValue(__instance) && !SaveSystem.loadedRun)
			{
				Run.PendingStart = true;
			}
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)ex.Message);
		}
	}

	private static void WorldStartPostfix(WorldGeneration __instance)
	{
		try
		{
			Run.OnWorldStart(__instance);
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)ex.Message);
		}
	}

	private static void EscapePrefix()
	{
		Run.Finish("escape");
	}

	private static void BiopodPrefix()
	{
		Run.Finish("biopod");
	}

	private static void MercPrefix()
	{
		Run.Finish("merc");
	}

	private static void ConsolePrefix()
	{
		Run.Flag("The console was used.");
	}

	private void Start()
	{
		try
		{
			Guard.Check(full: true);
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Guard: " + ex.Message));
		}
		if (Account.Ready)
		{
			((MonoBehaviour)this).StartCoroutine(Guard.AskWhitelist());
		}
	}

	private void Update()
	{
		//IL_0055: Unknown result type (might be due to invalid IL or missing references)
		try
		{
			Guard.Check(full: false);
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("Guard: " + ex.Message));
		}
		try
		{
			Run.Tick();
		}
		catch (Exception ex2)
		{
			Log.LogWarning((object)("Tick: " + ex2.Message));
		}
		if (!Ui.WaitingKey && Input.GetKeyDown(BoardKey.Value))
		{
			Ui.ToggleBoard();
		}
	}

	private void OnGUI()
	{
		try
		{
			Ui.Draw();
		}
		catch (Exception ex)
		{
			Log.LogWarning((object)("UI: " + ex.Message));
		}
	}
}
internal static class Account
{
	public static string Id;

	public static string Token;

	public static string Name;

	public static bool Dismissed;

	private static string FilePath => Path.Combine(Paths.ConfigPath, "speedruncu.account");

	public static bool Ready
	{
		get
		{
			if (!string.IsNullOrEmpty(Id))
			{
				return !string.IsNullOrEmpty(Token);
			}
			return false;
		}
	}

	public static void Load()
	{
		try
		{
			if (File.Exists(FilePath))
			{
				string[] array = File.ReadAllLines(FilePath);
				if (array.Length >= 3)
				{
					Id = array[0].Trim();
					Token = array[1].Trim();
					Name = array[2].Trim();
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Couldn't read your speedrun account: " + ex.Message));
		}
	}

	public static void Save(string id, string token, string name)
	{
		Id = id;
		Token = token;
		Name = name;
		File.WriteAllText(FilePath, id + "\n" + token + "\n" + name + "\n");
	}

	public static string NameProblem(string name)
	{
		if (name == null)
		{
			return "Type a name.";
		}
		name = name.Trim();
		if (name.Length < 3 || name.Length > 16)
		{
			return "Names are 3 to 16 characters.";
		}
		string text = name;
		foreach (char c in text)
		{
			if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != ' ' && c != '_' && c != '.' && c != '-')
			{
				return "Use letters, numbers, spaces, _ . or - only.";
			}
		}
		return null;
	}
}
internal class Resp
{
	public long Code;

	public bool Net;

	public JObject Json;

	public string Error
	{
		get
		{
			if (Json == null || Json["error"] == null)
			{
				return null;
			}
			return (string)Json["error"];
		}
	}

	public string Reason
	{
		get
		{
			if (Json == null || Json["reason"] == null)
			{
				return null;
			}
			return (string)Json["reason"];
		}
	}
}
internal static class Net
{
	public static bool UpdateRequired;

	public static string MinVersion;

	public static IEnumerator Call(string method, string path, string body, bool auth, Resp into)
	{
		UnityWebRequest req = new UnityWebRequest("https://speedrun.smellypawz.com" + path, method);
		if (body != null)
		{
			req.uploadHandler = (UploadHandler)new UploadHandlerRaw(Encoding.UTF8.GetBytes(body));
			req.uploadHandler.contentType = "application/json";
		}
		req.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
		if (auth && Account.Ready)
		{
			req.SetRequestHeader("Authorization", "Bearer " + Account.Id + "." + Account.Token);
		}
		req.SetRequestHeader("X-SR-Version", "1.0.0");
		req.timeout = 20;
		yield return req.SendWebRequest();
		into.Code = req.responseCode;
		into.Net = (int)req.result == 2 || req.responseCode == 0;
		string text = ((req.downloadHandler != null) ? req.downloadHandler.text : null);
		req.Dispose();
		if (!string.IsNullOrEmpty(text) && text.TrimStart().StartsWith("{"))
		{
			try
			{
				into.Json = JObject.Parse(text);
			}
			catch
			{
				into.Json = null;
			}
		}
		if (into.Code == 426)
		{
			UpdateRequired = true;
			MinVersion = ((into.Json != null && into.Json["minVersion"] != null) ? ((string)into.Json["minVersion"]) : "");
		}
	}

	public static string Str(string s)
	{
		StringBuilder stringBuilder = new StringBuilder("\"");
		foreach (char c in s)
		{
			if (c == '"' || c == '\\')
			{
				stringBuilder.Append('\\').Append(c);
			}
			else if (c < ' ')
			{
				stringBuilder.Append(' ');
			}
			else
			{
				stringBuilder.Append(c);
			}
		}
		return stringBuilder.Append('"').ToString();
	}

	public static string I(long v)
	{
		return v.ToString(CultureInfo.InvariantCulture);
	}
}
internal class Split
{
	public int Depth;

	public long Igt;

	public long Rta;
}
internal class Job
{
	public string Path;

	public string Body;

	public bool IsStart;

	public bool IsFinish;

	public bool IsSplit;
}
internal static class Guard
{
	public static bool Locked;

	public static bool Whitelisted;

	public static bool Hidden;

	public static readonly List<string> Found = new List<string>();

	private static readonly string[] CheatWords = new string[13]
	{
		"cheat", "trainer", "hack", "godmode", "god mode", "unityexplorer", "unity explorer", "runtimeunityeditor", "runtime unity editor", "infinite",
		"invincib", "noclip", "speedhack"
	};

	private static readonly string[] CheatAssemblies = new string[8] { "cucheats", "cucheatsml", "unityexplorer", "unityexplorer.bie5.mono", "unityexplorer.bie.mono", "runtimeunityeditor", "runtimeunityeditor.bepinex5", "universelib.mono" };

	private static readonly string[] CheatProcesses = new string[5] { "cheatengine", "cheat engine", "ultra paradise cu-trainer", "artmoney", "wemod" };

	private static int asmCount;

	private static float nextCheck;

	private static float nextProcess;

	public static IEnumerator AskWhitelist()
	{
		Resp r = new Resp();
		yield return Net.Call("GET", "/v1/me", null, auth: true, r);
		if (r.Code == 200 && r.Json != null)
		{
			SetWhitelisted(r.Json["whitelisted"] != null && (int)r.Json["whitelisted"].Type == 9 && (bool)r.Json["whitelisted"]);
		}
	}

	public static void SetWhitelisted(bool on)
	{
		if (on != Whitelisted)
		{
			Whitelisted = on;
			if (on)
			{
				Locked = false;
				Plugin.Log.LogInfo((object)"Your account is whitelisted: cheats are allowed, and cheated runs are saved as test runs that never show on the boards.");
			}
			else if (Found.Count > 0)
			{
				Locked = true;
			}
		}
	}

	public static void Check(bool full)
	{
		float realtimeSinceStartup = Time.realtimeSinceStartup;
		if (!full && realtimeSinceStartup < nextCheck)
		{
			return;
		}
		nextCheck = realtimeSinceStartup + 3f;
		foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
		{
			if (pluginInfo.Value != null && !(pluginInfo.Key == "speedruncu"))
			{
				string text = ((pluginInfo.Value.Metadata != null) ? pluginInfo.Value.Metadata.Name : pluginInfo.Key);
				if (LooksLikeCheat(pluginInfo.Key) || LooksLikeCheat(text))
				{
					Lock(text);
				}
			}
		}
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		if (assemblies.Length != asmCount)
		{
			asmCount = assemblies.Length;
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				string value = "";
				try
				{
					value = (assembly.GetName().Name ?? "").ToLowerInvariant();
				}
				catch
				{
				}
				if (Array.IndexOf(CheatAssemblies, value) >= 0)
				{
					Lock(assembly.GetName().Name);
				}
				try
				{
					if (assembly.GetType("UltraParadise.Link", throwOnError: false) != null || assembly.GetType("UltraParadise.Loader", throwOnError: false) != null)
					{
						Lock("Ultra Paradise CU:Trainer");
					}
				}
				catch
				{
				}
			}
		}
		if (SteamManager.disableAchievements)
		{
			Lock("the game's cheat console (or a save made with cheats)");
		}
		if (!full && !(realtimeSinceStartup >= nextProcess))
		{
			return;
		}
		nextProcess = realtimeSinceStartup + 15f;
		try
		{
			Process[] processes = Process.GetProcesses();
			foreach (Process process in processes)
			{
				string text2 = "";
				try
				{
					text2 = process.ProcessName.ToLowerInvariant();
				}
				catch
				{
				}
				string[] cheatProcesses = CheatProcesses;
				foreach (string value2 in cheatProcesses)
				{
					if (text2.Contains(value2))
					{
						Lock(process.ProcessName);
						break;
					}
				}
				process.Dispose();
			}
		}
		catch
		{
		}
	}

	private static bool LooksLikeCheat(string s)
	{
		s = (s ?? "").ToLowerInvariant();
		string[] cheatWords = CheatWords;
		foreach (string value in cheatWords)
		{
			if (s.Contains(value))
			{
				return true;
			}
		}
		return false;
	}

	private static void Lock(string what)
	{
		if (!Found.Contains(what))
		{
			Found.Add(what);
			if (!Locked)
			{
				Plugin.Log.LogWarning((object)("Speedrun CU is switched off: cheating isn't allowed. Found: " + what));
			}
			Run.Flag("Cheats were found: " + what);
			if (!Whitelisted)
			{
				Locked = true;
				Hidden = false;
			}
		}
	}
}
internal static class Run
{
	public static readonly string[] AllowedPlugins = new string[8] { "speedruncu", "controllersupport", "hatshatshats", "bossmusic", "doomdeathscreen", "com.bepis.bepinex.configurationmanager", "configurationmanager", "com.bepis.bepinex.scriptengine" };

	public static readonly string[] AllowedOwners = new string[5] { "speedruncu", "controllersupport", "hatshatshats", "bossmusic", "customdeathscreen" };

	public static readonly string[] PresetNames = new string[5] { "normal", "relaxed", "paradise", "desolate", "unchipped" };

	public static bool PendingStart;

	public static bool BrokenHooks;

	public static bool Active;

	public static bool Finished;

	public static bool Ranked;

	public static string Invalid;

	public static string Preset;

	public static int Character;

	public static int Depth;

	public static string Ending;

	public static string ServerRun;

	public static string Result;

	public static bool ResultGood;

	public static float ResultUntil;

	public static readonly List<Split> Splits = new List<Split>();

	private static readonly Stopwatch watch = new Stopwatch();

	private static double lastMs;

	private static double igt;

	private static double paused;

	private static double loading;

	private static bool achievementsWereOff;

	private static int asmCount;

	private static float nextScan;

	private static readonly Queue<Job> jobs = new Queue<Job>();

	private static bool working;

	private static int workerGen = -1;

	private static int generation;

	public static bool Cheated;

	public static string CheatNote;

	private static readonly FieldInfo regenField = AccessTools.Field(typeof(WorldGeneration), "doingRegen");

	private static Type saLoader;

	private static FieldInfo saRestoring;

	private static bool saLooked;

	public static long Igt => (long)igt;

	public static long Rta => (long)watch.Elapsed.TotalMilliseconds;

	public static void OnWorldStart(WorldGeneration w)
	{
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		bool pendingStart = PendingStart;
		PendingStart = false;
		Reset();
		if (!pendingStart || Guard.Locked || (int)w.biomeOverride != 0)
		{
			return;
		}
		Body val = (((Object)(object)PlayerCamera.main != (Object)null) ? PlayerCamera.main.body : null);
		if (!((Object)(object)val == (Object)null))
		{
			Active = true;
			Character = val.charType;
			Depth = w.biomeDepth;
			Preset = MatchPreset();
			achievementsWereOff = SteamManager.disableAchievements;
			asmCount = 0;
			watch.Reset();
			watch.Start();
			lastMs = 0.0;
			Ranked = true;
			if (BrokenHooks)
			{
				Invalidate("Speedrun CU couldn't hook the game. Check for a mod update.");
			}
			if (Preset == null)
			{
				Invalidate("Only the standard difficulty presets are ranked, not custom or endless settings.");
			}
			string text = BadPlugins();
			if (text != null)
			{
				Flag("Mods that change gameplay are loaded: " + text);
			}
			if (Guard.Found.Count > 0)
			{
				Flag("Cheats were found: " + string.Join(", ", Guard.Found.ToArray()));
			}
			Scan();
			if (!Account.Ready)
			{
				Invalidate("Make a speedrun name in the main menu to get ranked.");
			}
			if (Net.UpdateRequired)
			{
				Invalidate("Update Speedrun CU to get ranked.");
			}
			if (Ranked)
			{
				string body = "{\"preset\":" + Net.Str(Preset) + ",\"character\":" + Net.I(Character) + ",\"depth\":" + Net.I(Depth) + ",\"gameVersion\":" + Net.Str(GameVersion()) + "}";
				Job job = new Job();
				job.Path = "/v1/run/start";
				job.Body = body;
				job.IsStart = true;
				Enqueue(job);
			}
		}
	}

	private static void Reset()
	{
		Active = false;
		Finished = false;
		Ranked = false;
		Invalid = null;
		Cheated = false;
		CheatNote = null;
		Ending = null;
		ServerRun = null;
		Splits.Clear();
		jobs.Clear();
		igt = (paused = (loading = 0.0));
		watch.Reset();
		generation++;
	}

	public static void Flag(string why)
	{
		if (Guard.Whitelisted)
		{
			if (Active && !Finished)
			{
				if (!Cheated)
				{
					Plugin.Log.LogInfo((object)("Test run (whitelisted account): " + why));
				}
				Cheated = true;
				if (CheatNote == null)
				{
					CheatNote = why;
				}
			}
		}
		else
		{
			Invalidate(why);
		}
	}

	public static void Invalidate(string why)
	{
		if (Active && !Finished)
		{
			if (Invalid == null)
			{
				Invalid = why;
				Plugin.Log.LogInfo((object)("This run won't be ranked: " + why));
			}
			Ranked = false;
			jobs.Clear();
		}
	}

	public static void Tick()
	{
		if (!Active || Finished)
		{
			return;
		}
		WorldGeneration world = WorldGeneration.world;
		PlayerCamera main = PlayerCamera.main;
		if ((Object)(object)world == (Object)null || (Object)(object)main == (Object)null || (Object)(object)main.body == (Object)null)
		{
			Reset();
			return;
		}
		Count(world);
		if (!main.body.alive && !world.cutsceneActive)
		{
			Reset();
			return;
		}
		if (Ranked)
		{
			if (SteamManager.disableAchievements && !achievementsWereOff)
			{
				Flag("The console was used.");
			}
			if (Time.timeScale > 25.5f)
			{
				Flag("Game speed was changed beyond the game's own speeds.");
			}
			if (SaveAnywhereRestoring())
			{
				Invalidate("A save was loaded during the run.");
			}
			if (Time.realtimeSinceStartup >= nextScan)
			{
				nextScan = Time.realtimeSinceStartup + 5f;
				Scan();
			}
		}
		if (world.biomeDepth != Depth)
		{
			int biomeDepth = world.biomeDepth;
			if (biomeDepth < Depth)
			{
				Invalidate("The layer order changed in a way a normal run can't.");
			}
			Depth = biomeDepth;
			Split split = new Split();
			split.Depth = biomeDepth;
			split.Igt = Igt;
			split.Rta = Rta;
			Split split2 = split;
			Splits.Add(split2);
			if (Ranked)
			{
				Job job = new Job();
				job.Path = "/v1/run/split";
				job.IsSplit = true;
				job.Body = "{\"run\":\"@RUN@\",\"depth\":" + Net.I(biomeDepth) + ",\"igt\":" + Net.I(split2.Igt) + ",\"rta\":" + Net.I(split2.Rta) + "}";
				Enqueue(job);
			}
		}
	}

	private static bool Regenerating(WorldGeneration w)
	{
		try
		{
			return regenField != null && (bool)regenField.GetValue(w);
		}
		catch
		{
			return false;
		}
	}

	private static void Count(WorldGeneration w)
	{
		double totalMilliseconds = watch.Elapsed.TotalMilliseconds;
		double num = totalMilliseconds - lastMs;
		lastMs = totalMilliseconds;
		if (!(num <= 0.0))
		{
			if (PauseHandler.paused)
			{
				paused += num;
			}
			else if (w.generatingWorld || Regenerating(w))
			{
				loading += num;
			}
			else
			{
				igt += num;
			}
		}
	}

	public static void Finish(string ending)
	{
		if (!Active || Finished)
		{
			return;
		}
		if (Guard.Locked)
		{
			Reset();
			return;
		}
		WorldGeneration world = WorldGeneration.world;
		if ((Object)(object)world != (Object)null)
		{
			Count(world);
		}
		watch.Stop();
		Finished = true;
		Ending = ending;
		string text = Ui.Time(Igt);
		if (!Ranked)
		{
			ShowResult("Finished in " + text + ". Not ranked: " + (Invalid ?? "unknown reason."), good: false);
			return;
		}
		ShowResult("Finished in " + text + ". Sending to the leaderboard...", good: true);
		StringBuilder stringBuilder = new StringBuilder("[");
		bool flag = true;
		foreach (string item in PluginGuids())
		{
			if (!flag)
			{
				stringBuilder.Append(',');
			}
			stringBuilder.Append(Net.Str(Clean(item)));
			flag = false;
		}
		stringBuilder.Append(']');
		long rta = Rta;
		long num = Igt;
		long num2 = (long)paused;
		long num3 = rta - num - num2;
		if (num3 < 0)
		{
			num3 = 0L;
		}
		string body = string.Concat("{\"run\":\"@RUN@\",\"ending\":", Net.Str(ending), ",\"depth\":", Net.I(((Object)(object)world != (Object)null) ? world.biomeDepth : Depth), ",\"igt\":", Net.I(num), ",\"rta\":", Net.I(rta), ",\"paused\":", Net.I(num2), ",\"loading\":", Net.I(num3), ",\"plugins\":", stringBuilder, ",\"cheated\":", (Cheated || Guard.Found.Count > 0) ? "true" : "false", "}");
		Job job = new Job();
		job.Path = "/v1/run/finish";
		job.Body = body;
		job.IsFinish = true;
		Enqueue(job);
	}

	public static void ShowResult(string text, bool good)
	{
		Result = text;
		ResultGood = good;
		ResultUntil = Time.realtimeSinceStartup + 25f;
		Plugin.Log.LogInfo((object)text);
	}

	private static void Enqueue(Job j)
	{
		jobs.Enqueue(j);
		if (!working || workerGen != generation)
		{
			working = true;
			workerGen = generation;
			((MonoBehaviour)Plugin.Instance).StartCoroutine(Worker(generation));
		}
	}

	private static IEnumerator Worker(int gen)
	{
		while (true)
		{
			if (jobs.Count > 0 && gen == generation)
			{
				Job j = jobs.Peek();
				if (j.IsStart || ServerRun != null)
				{
					string body = j.Body.Replace("@RUN@", ServerRun ?? "");
					int tries = 0;
					Resp r;
					while (true)
					{
						r = new Resp();
						yield return Net.Call("POST", j.Path, body, auth: true, r);
						if (gen == generation)
						{
							tries++;
							if ((!r.Net && r.Code != 429 && r.Code < 500) || tries >= (j.IsFinish ? 8 : 4))
							{
								break;
							}
							yield return (object)new WaitForSecondsRealtime(Math.Min(30f, 3f * (float)tries));
							continue;
						}
						yield break;
					}
					if (jobs.Count > 0 && jobs.Peek() == j)
					{
						jobs.Dequeue();
					}
					Handle(j, r);
					continue;
				}
				jobs.Clear();
			}
			if (gen == generation)
			{
				working = false;
			}
			break;
		}
	}

	private static void Handle(Job j, Resp r)
	{
		//IL_010f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Invalid comparison between Unknown and I4
		if (r.Code == 200 && r.Json != null)
		{
			if (j.IsStart)
			{
				ServerRun = (string)r.Json["run"];
			}
			else
			{
				if (!j.IsFinish)
				{
					return;
				}
				string text = (string)r.Json["status"];
				bool flag = r.Json["pb"] != null && (bool)r.Json["pb"];
				JToken val = r.Json["rank"];
				string text2 = Ui.BoardName(Ending, Preset);
				string text3 = Ui.Time(Igt);
				if (text == "test")
				{
					ShowResult("Test run saved: " + text3 + " on " + text2 + ". Cheats were on, so it isn't ranked.", good: true);
				}
				else if (flag && val != null && (int)val.Type == 6)
				{
					string text4 = "New personal best: " + text3 + " (#" + (int)val + " on " + text2 + ")";
					if (text == "review")
					{
						text4 += ". Top runs are checked by hand before they show up.";
					}
					ShowResult(text4, good: true);
				}
				else
				{
					ShowResult("Run saved: " + text3 + " on " + text2 + ". Not a personal best.", good: true);
				}
				Ui.RefreshSoon();
			}
		}
		else
		{
			string text5 = ((r.Code == 409 && r.Error == "run_rejected") ? (r.Reason ?? "The server rejected the run.") : ((r.Code == 426) ? ("Update Speedrun CU to version " + Net.MinVersion + " or newer.") : ((r.Code == 401) ? "Your speedrun account wasn't recognised." : ((r.Code == 403 && r.Error == "banned") ? "This account is banned from the leaderboard." : ((r.Code == 503) ? "The leaderboard is paused right now." : ((r.Code == 429) ? "Too many requests. Try again later." : ((!r.Net) ? ("The leaderboard said no (" + r.Code + ((r.Error != null) ? (", " + r.Error) : "") + ").") : "Couldn't reach the leaderboard.")))))));
			if (j.IsFinish)
			{
				ShowResult("Finished in " + Ui.Time(Igt) + ". Not ranked: " + text5, good: false);
			}
			else
			{
				Invalidate(text5);
			}
			Ranked = false;
			if (Invalid == null)
			{
				Invalid = text5;
			}
			jobs.Clear();
		}
	}

	private static string MatchPreset()
	{
		Dictionary<string, object> runSettings = WorldGeneration.runSettings;
		if (runSettings == null)
		{
			return null;
		}
		RunSettingsPreset preset = RunSettings.GetPreset("normal");
		string[] presetNames = PresetNames;
		foreach (string text in presetNames)
		{
			RunSettingsPreset preset2;
			try
			{
				preset2 = RunSettings.GetPreset(text);
			}
			catch
			{
				continue;
			}
			Dictionary<string, object> dictionary = new Dictionary<string, object>(preset.presetValues);
			foreach (KeyValuePair<string, object> presetValue in preset2.presetValues)
			{
				dictionary[presetValue.Key] = presetValue.Value;
			}
			if (dictionary.Count != runSettings.Count)
			{
				continue;
			}
			bool flag = true;
			foreach (KeyValuePair<string, object> item in dictionary)
			{
				if (!runSettings.TryGetValue(item.Key, out var value) || !Same(item.Value, value))
				{
					flag = false;
					break;
				}
			}
			if (flag)
			{
				return text;
			}
		}
		return null;
	}

	private static bool Same(object a, object b)
	{
		if (a == null || b == null)
		{
			return a == b;
		}
		if (a is bool || b is bool)
		{
			return a.ToString().ToLowerInvariant() == b.ToString().ToLowerInvariant();
		}
		try
		{
			double num = Convert.ToDouble(a, CultureInfo.InvariantCulture);
			double num2 = Convert.ToDouble(b, CultureInfo.InvariantCulture);
			return Math.Abs(num - num2) < 0.0001;
		}
		catch
		{
			return a.ToString() == b.ToString();
		}
	}

	public static IEnumerable<string> PluginGuids()
	{
		foreach (KeyValuePair<string, PluginInfo> kv in Chainloader.PluginInfos)
		{
			KeyValuePair<string, PluginInfo> keyValuePair = kv;
			if (keyValuePair.Value != null)
			{
				KeyValuePair<string, PluginInfo> keyValuePair2 = kv;
				if ((Object)(object)keyValuePair2.Value.Instance != (Object)null)
				{
					KeyValuePair<string, PluginInfo> keyValuePair3 = kv;
					yield return keyValuePair3.Key;
				}
			}
		}
	}

	public static string BadPlugins()
	{
		List<string> list = new List<string>();
		foreach (KeyValuePair<string, PluginInfo> pluginInfo in Chainloader.PluginInfos)
		{
			if (pluginInfo.Value != null && !((Object)(object)pluginInfo.Value.Instance == (Object)null) && Array.IndexOf(AllowedPlugins, pluginInfo.Key.ToLowerInvariant()) < 0)
			{
				list.Add((pluginInfo.Value.Metadata != null) ? pluginInfo.Value.Metadata.Name : pluginInfo.Key);
			}
		}
		if (list.Count <= 0)
		{
			return null;
		}
		return string.Join(", ", list.ToArray());
	}

	private static void Scan()
	{
		Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
		if (assemblies.Length != asmCount)
		{
			asmCount = assemblies.Length;
			Assembly[] array = assemblies;
			foreach (Assembly assembly in array)
			{
				try
				{
					if (assembly.GetType("UltraParadise.Link", throwOnError: false) != null || assembly.GetType("UltraParadise.Loader", throwOnError: false) != null)
					{
						Flag("A cheat trainer is attached to the game.");
						return;
					}
				}
				catch
				{
				}
			}
		}
		try
		{
			foreach (MethodBase allPatchedMethod in Harmony.GetAllPatchedMethods())
			{
				Patches patchInfo = Harmony.GetPatchInfo(allPatchedMethod);
				if (patchInfo == null)
				{
					continue;
				}
				foreach (string owner in patchInfo.Owners)
				{
					string text = (owner ?? "").ToLowerInvariant();
					if (Array.IndexOf(AllowedOwners, text) < 0 && !text.StartsWith("bepinex") && !text.StartsWith("com.bepis"))
					{
						Flag("Another mod changes the game (" + Clean(owner) + ").");
						return;
					}
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Patch scan: " + ex.Message));
		}
	}

	private static bool SaveAnywhereRestoring()
	{
		if (!saLooked)
		{
			saLooked = true;
			Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
			foreach (Assembly assembly in assemblies)
			{
				try
				{
					saLoader = assembly.GetType("SaveAnywhere.Loader", throwOnError: false);
				}
				catch
				{
				}
				if (saLoader != null)
				{
					break;
				}
			}
			if (saLoader != null)
			{
				saRestoring = saLoader.GetField("Restoring", BindingFlags.Static | BindingFlags.Public);
			}
		}
		if (saRestoring == null)
		{
			return false;
		}
		try
		{
			return (bool)saRestoring.GetValue(null);
		}
		catch
		{
			return false;
		}
	}

	private static string Clean(string s)
	{
		StringBuilder stringBuilder = new StringBuilder();
		string text = s ?? "";
		foreach (char c in text)
		{
			if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' || c == ' ')
			{
				stringBuilder.Append(c);
			}
		}
		string text2 = stringBuilder.ToString();
		if (text2.Length == 0)
		{
			text2 = "unknown";
		}
		if (text2.Length <= 64)
		{
			return text2;
		}
		return text2.Substring(0, 64);
	}

	private static string GameVersion()
	{
		string s = Application.version ?? "unknown";
		return Clean(s).Replace(" ", "");
	}
}
internal class Entry
{
	public int Rank;

	public string Name;

	public long Igt;

	public int Character;
}
internal static class Ui
{
	private static readonly string[] Endings = new string[3] { "escape", "biopod", "merc" };

	private static readonly string[] EndingLabels = new string[3] { "Escape", "Biopod", "Merc" };

	private static readonly string[] PresetLabels = new string[5] { "Normal", "Relaxed", "Paradise", "Desolate", "Unchipped" };

	private static readonly string[] CharLabels = new string[4] { "All", "Experiment", "Milky", "Dune" };

	private static bool boardOpen;

	private static int page;

	public static bool WaitingKey;

	private static readonly string[] Pages = new string[2] { "Leaderboard", "Settings" };

	private static readonly string[] Corners = new string[4] { "Top right", "Top left", "Bottom right", "Bottom left" };

	private static int endingIdx;

	private static int presetIdx;

	private static int charIdx;

	private static string boardStatus = "";

	private static readonly List<Entry> entries = new List<Entry>();

	private static int pending;

	private static bool loadingBoard;

	private static float refreshAt = -1f;

	private static string myPbs = "";

	private static string nameInput = "";

	private static string nameStatus = "";

	private static bool registering;

	private static Rect boardRect = new Rect(0f, 0f, 520f, 470f);

	private static Rect nameRect = new Rect(0f, 0f, 430f, 210f);

	private static GUIStyle box;

	private static GUIStyle title;

	private static GUIStyle small;

	private static GUIStyle good;

	private static GUIStyle bad;

	private static GUIStyle big;

	private static GUIStyle row;

	private static Texture2D dark;

	public static void ToggleBoard()
	{
		if (Guard.Locked && !Guard.Whitelisted)
		{
			Guard.Hidden = !Guard.Hidden;
			boardOpen = false;
			return;
		}
		boardOpen = !boardOpen;
		if (boardOpen)
		{
			((Rect)(ref boardRect)).x = ((float)Screen.width - ((Rect)(ref boardRect)).width) / 2f;
			((Rect)(ref boardRect)).y = ((float)Screen.height - ((Rect)(ref boardRect)).height) / 2f;
			if (Run.Preset != null)
			{
				presetIdx = Math.Max(0, Array.IndexOf(Run.PresetNames, Run.Preset));
			}
			LoadBoard();
		}
	}

	public static void RefreshSoon()
	{
		refreshAt = Time.realtimeSinceStartup + 2f;
	}

	public static string Time(long ms)
	{
		if (ms < 0)
		{
			ms = 0L;
		}
		long num = ms / 3600000;
		long num2 = ms / 60000 % 60;
		long num3 = ms / 1000 % 60;
		long num4 = ms % 1000;
		string text = num2.ToString("00") + ":" + num3.ToString("00") + "." + num4.ToString("000");
		if (num <= 0)
		{
			return text;
		}
		return num + ":" + text;
	}

	public static string BoardName(string ending, string preset)
	{
		int num = Array.IndexOf(Endings, ending);
		int num2 = Array.IndexOf(Run.PresetNames, preset);
		return ((num >= 0) ? EndingLabels[num] : ending) + " / " + ((num2 >= 0) ? PresetLabels[num2] : preset);
	}

	private static void Styles()
	{
		//IL_000a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Expected O, but got Unknown
		//IL_002f: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Expected O, but got Unknown
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0080: Expected O, but got Unknown
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0090: Expected O, but got Unknown
		//IL_00be: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d8: Expected O, but got Unknown
		//IL_0106: 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_011f: Expected O, but got Unknown
		//IL_0138: Unknown result type (might be due to invalid IL or missing references)
		//IL_0147: Unknown result type (might be due to invalid IL or missing references)
		//IL_0151: Expected O, but got Unknown
		//IL_016a: Unknown result type (might be due to invalid IL or missing references)
		//IL_017e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0184: Expected O, but got Unknown
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_01be: Unknown result type (might be due to invalid IL or missing references)
		//IL_01c4: Expected O, but got Unknown
		//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
		if (box == null)
		{
			dark = new Texture2D(1, 1);
			dark.SetPixel(0, 0, new Color(0.05f, 0.05f, 0.07f, 0.86f));
			dark.Apply();
			box = new GUIStyle(GUI.skin.box);
			box.normal.background = dark;
			box.padding = new RectOffset(10, 10, 6, 6);
			GUIStyle val = new GUIStyle(GUI.skin.label);
			val.fontSize = 16;
			val.fontStyle = (FontStyle)1;
			title = val;
			title.normal.textColor = new Color(1f, 0.72f, 0.3f);
			GUIStyle val2 = new GUIStyle(GUI.skin.label);
			val2.fontSize = 12;
			val2.wordWrap = true;
			small = val2;
			small.normal.textColor = new Color(0.82f, 0.82f, 0.86f);
			good = new GUIStyle(small);
			good.normal.textColor = new Color(0.5f, 0.95f, 0.55f);
			bad = new GUIStyle(small);
			bad.normal.textColor = new Color(1f, 0.45f, 0.42f);
			GUIStyle val3 = new GUIStyle(GUI.skin.label);
			val3.fontSize = 26;
			val3.fontStyle = (FontStyle)1;
			val3.alignment = (TextAnchor)5;
			big = val3;
			big.normal.textColor = Color.white;
			GUIStyle val4 = new GUIStyle(GUI.skin.label);
			val4.fontSize = 13;
			row = val4;
			row.normal.textColor = Color.white;
		}
	}

	public static void Draw()
	{
		//IL_0018: Unknown result type (might be due to invalid IL or missing references)
		//IL_001e: Invalid comparison between Unknown and I4
		//IL_0025: Unknown result type (might be due to invalid IL or missing references)
		//IL_0031: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Invalid comparison between Unknown and I4
		//IL_0044: Unknown result type (might be due to invalid IL or missing references)
		//IL_0130: Unknown result type (might be due to invalid IL or missing references)
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Expected O, but got Unknown
		//IL_0146: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		Styles();
		if (WaitingKey && Event.current != null && (int)Event.current.type == 4 && (int)Event.current.keyCode != 0)
		{
			if ((int)Event.current.keyCode != 27)
			{
				Plugin.BoardKey.Value = Event.current.keyCode;
			}
			WaitingKey = false;
			Event.current.Use();
		}
		if (refreshAt > 0f && Time.realtimeSinceStartup > refreshAt)
		{
			refreshAt = -1f;
			if (boardOpen)
			{
				LoadBoard();
			}
		}
		if (Guard.Locked)
		{
			DrawLocked();
			if ((Object)(object)PlayerCamera.main == (Object)null && !Account.Ready && !Account.Dismissed && !Net.UpdateRequired)
			{
				DrawNamePrompt();
			}
			return;
		}
		if (Run.Active && (Object)(object)PlayerCamera.main != (Object)null && Plugin.ShowTimer.Value)
		{
			DrawTimer();
		}
		if (Run.Result != null && Time.realtimeSinceStartup < Run.ResultUntil)
		{
			DrawResult();
		}
		if ((Object)(object)PlayerCamera.main == (Object)null && !Account.Ready && !Account.Dismissed && !Net.UpdateRequired)
		{
			DrawNamePrompt();
		}
		if (boardOpen)
		{
			boardRect = GUI.Window(96534510, boardRect, new WindowFunction(BoardWindow), "Speedrun CU leaderboard");
		}
	}

	private static void DrawLocked()
	{
		//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
		//IL_0112: Unknown result type (might be due to invalid IL or missing references)
		//IL_0029: Unknown result type (might be due to invalid IL or missing references)
		//IL_0065: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
		if (Guard.Hidden)
		{
			Rect val = default(Rect);
			((Rect)(ref val))..ctor((float)(Screen.width - 250), 10f, 240f, 26f);
			GUI.Box(val, GUIContent.none, box);
			GUI.Label(new Rect(((Rect)(ref val)).x + 8f, ((Rect)(ref val)).y + 4f, ((Rect)(ref val)).width - 16f, 20f), "Speedrun CU: off (cheats found)", bad);
			return;
		}
		float num = Math.Min(520, Screen.width - 40);
		float num2 = 190 + Math.Min(Guard.Found.Count, 5) * 18;
		Rect val2 = default(Rect);
		((Rect)(ref val2))..ctor(((float)Screen.width - num) / 2f, ((float)Screen.height - num2) / 2f, num, num2);
		GUI.Box(val2, GUIContent.none, box);
		GUILayout.BeginArea(new Rect(((Rect)(ref val2)).x + 16f, ((Rect)(ref val2)).y + 12f, ((Rect)(ref val2)).width - 32f, ((Rect)(ref val2)).height - 24f));
		GUILayout.Label("SPEEDRUN CU IS OFF", title, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label("Cheating isn't allowed for this. Speedrun CU won't time or submit runs while cheats are around.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Space(4f);
		GUILayout.Label("Found:", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		for (int i = 0; i < Guard.Found.Count && i < 5; i++)
		{
			GUILayout.Label("  - " + Guard.Found[i], bad, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		GUILayout.Space(4f);
		GUILayout.Label("Remove or close it, then restart the game.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.FlexibleSpace();
		if (GUILayout.Button(string.Concat("Hide (", Plugin.BoardKey.Value, " shows this again)"), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(26f) }))
		{
			Guard.Hidden = true;
		}
		GUILayout.EndArea();
	}

	private static void DrawTimer()
	{
		//IL_0079: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		//IL_009b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_014f: Unknown result type (might be due to invalid IL or missing references)
		//IL_01de: Unknown result type (might be due to invalid IL or missing references)
		int num = (Plugin.ShowSplits.Value ? Math.Min(Run.Splits.Count, 10) : 0);
		float num2 = 64 + num * 18;
		int value = Plugin.TimerCorner.Value;
		float num3 = ((value == 1 || value == 3) ? 10 : (Screen.width - 250));
		float num4 = ((value >= 2) ? ((float)Screen.height - num2 - 10f) : 10f);
		Rect val = default(Rect);
		((Rect)(ref val))..ctor(num3, num4, 240f, num2);
		GUI.Box(val, GUIContent.none, box);
		big.normal.textColor = (Color)(Run.Finished ? new Color(1f, 0.85f, 0.3f) : Color.white);
		GUI.Label(new Rect(((Rect)(ref val)).x + 8f, ((Rect)(ref val)).y + 2f, ((Rect)(ref val)).width - 16f, 34f), Time(Run.Igt), big);
		string text = ((!Run.Ranked) ? "Not ranked" : (Run.Cheated ? "Test run (cheats on)" : "Ranked run"));
		GUI.Label(new Rect(((Rect)(ref val)).x + 8f, ((Rect)(ref val)).y + 38f, ((Rect)(ref val)).width - 16f, 20f), text + "  ·  Layer " + (Run.Depth + 1), Run.Ranked ? good : bad);
		int num5 = Run.Splits.Count - num;
		for (int i = 0; i < num; i++)
		{
			Split split = Run.Splits[num5 + i];
			GUI.Label(new Rect(((Rect)(ref val)).x + 8f, ((Rect)(ref val)).y + 60f + (float)(i * 18), ((Rect)(ref val)).width - 16f, 18f), "Layer " + (split.Depth + 1) + "   " + Time(split.Igt), small);
		}
	}

	private static void DrawResult()
	{
		//IL_0034: Unknown result type (might be due to invalid IL or missing references)
		//IL_0070: Unknown result type (might be due to invalid IL or missing references)
		float num = Math.Min(620, Screen.width - 40);
		Rect val = default(Rect);
		((Rect)(ref val))..ctor(((float)Screen.width - num) / 2f, 18f, num, 52f);
		GUI.Box(val, GUIContent.none, box);
		GUI.Label(new Rect(((Rect)(ref val)).x + 12f, ((Rect)(ref val)).y + 6f, ((Rect)(ref val)).width - 24f, 42f), Run.Result, Run.ResultGood ? good : bad);
	}

	private static void DrawNamePrompt()
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		((Rect)(ref nameRect)).x = 20f;
		((Rect)(ref nameRect)).y = (float)Screen.height - ((Rect)(ref nameRect)).height - 20f;
		GUI.Box(nameRect, GUIContent.none, box);
		GUILayout.BeginArea(new Rect(((Rect)(ref nameRect)).x + 12f, ((Rect)(ref nameRect)).y + 10f, ((Rect)(ref nameRect)).width - 24f, ((Rect)(ref nameRect)).height - 20f));
		GUILayout.Label("SPEEDRUN CU", title, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label("Pick a name for the online leaderboard. Everyone can see it, and you can't change it later.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUI.SetNextControlName("srname");
		nameInput = GUILayout.TextField(nameInput ?? "", 16, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUI.enabled = !registering;
		if (GUILayout.Button(registering ? "Saving..." : "Save name", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(26f) }))
		{
			string text = Account.NameProblem(nameInput);
			if (text != null)
			{
				nameStatus = text;
			}
			else
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Register(nameInput.Trim()));
			}
		}
		GUI.enabled = true;
		if (GUILayout.Button("Not now", (GUILayoutOption[])(object)new GUILayoutOption[2]
		{
			GUILayout.Width(90f),
			GUILayout.Height(26f)
		}))
		{
			Account.Dismissed = true;
		}
		GUILayout.EndHorizontal();
		if (nameStatus.Length > 0)
		{
			GUILayout.Label(nameStatus, bad, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		GUILayout.EndArea();
	}

	private static IEnumerator Register(string name)
	{
		registering = true;
		nameStatus = "";
		Resp r = new Resp();
		yield return Net.Call("POST", "/v1/register", "{\"name\":" + Net.Str(name) + "}", auth: false, r);
		registering = false;
		if (r.Code == 200 && r.Json != null && r.Json["id"] != null && r.Json["token"] != null)
		{
			try
			{
				Account.Save((string)r.Json["id"], (string)r.Json["token"], (string)r.Json["name"]);
				Run.ShowResult("You're on the board as " + Account.Name + ". Good luck!", good: true);
				yield break;
			}
			catch (Exception ex)
			{
				nameStatus = "Couldn't save your account file: " + ex.Message;
				yield break;
			}
		}
		if (r.Code == 409)
		{
			nameStatus = "That name is taken (or too close to one that is).";
		}
		else if (r.Code == 422)
		{
			nameStatus = r.Reason ?? "That name isn't allowed.";
		}
		else if (r.Code == 429)
		{
			nameStatus = "Too many tries. Wait a minute, or try again tomorrow.";
		}
		else if (r.Code == 426)
		{
			nameStatus = "Update Speedrun CU first.";
		}
		else if (r.Code == 503)
		{
			nameStatus = "The leaderboard isn't taking new names right now.";
		}
		else if (r.Net)
		{
			nameStatus = "Couldn't reach the leaderboard. Check your connection.";
		}
		else
		{
			nameStatus = "Something went wrong (" + r.Code + ").";
		}
	}

	private static void LoadBoard()
	{
		if (!loadingBoard)
		{
			((MonoBehaviour)Plugin.Instance).StartCoroutine(FetchBoard());
		}
	}

	private static IEnumerator FetchBoard()
	{
		loadingBoard = true;
		boardStatus = "Loading...";
		string q = "?ending=" + Endings[endingIdx] + "&preset=" + Run.PresetNames[presetIdx] + "&char=" + ((charIdx == 0) ? "all" : (charIdx - 1).ToString());
		Resp r = new Resp();
		yield return Net.Call("GET", "/v1/board" + q, null, auth: false, r);
		entries.Clear();
		pending = 0;
		if (r.Code == 200 && r.Json != null && r.Json["entries"] is JArray)
		{
			foreach (JToken item in (JArray)r.Json["entries"])
			{
				if (entries.Count < 15)
				{
					entries.Add(new Entry
					{
						Rank = (int)item[(object)"rank"],
						Name = (string)item[(object)"name"],
						Igt = (long)item[(object)"igt"],
						Character = (int)item[(object)"character"]
					});
					continue;
				}
				break;
			}
			pending = ((r.Json["pending"] != null) ? ((int)r.Json["pending"]) : 0);
			boardStatus = ((entries.Count == 0) ? "No runs yet. Be the first!" : "");
		}
		else if (r.Net)
		{
			boardStatus = "Couldn't reach the leaderboard.";
		}
		else
		{
			boardStatus = "The leaderboard is unavailable (" + r.Code + ").";
		}
		myPbs = "";
		if (Account.Ready)
		{
			Resp me = new Resp();
			yield return Net.Call("GET", "/v1/me", null, auth: true, me);
			if (me.Code == 200 && me.Json != null && me.Json["pbs"] is JArray)
			{
				Guard.SetWhitelisted(me.Json["whitelisted"] != null && (int)me.Json["whitelisted"].Type == 9 && (bool)me.Json["whitelisted"]);
				List<string> list = new List<string>();
				foreach (JToken item2 in (JArray)me.Json["pbs"])
				{
					string[] array = ((string)item2[(object)"board"]).Split(':');
					list.Add(BoardName(array[0], (array.Length > 1) ? array[1] : "") + " " + Time((long)item2[(object)"igt"]) + " (#" + (int)item2[(object)"rank"] + ")");
				}
				myPbs = ((list.Count > 0) ? ("Your bests: " + string.Join("   ", list.ToArray())) : "No ranked runs yet.");
			}
			else if (me.Code == 403)
			{
				myPbs = "This account is banned from the leaderboard.";
			}
		}
		loadingBoard = false;
	}

	private static void BoardWindow(int id)
	{
		//IL_0061: Unknown result type (might be due to invalid IL or missing references)
		//IL_035e: Unknown result type (might be due to invalid IL or missing references)
		GUILayout.Space(4f);
		page = GUILayout.Toolbar(page, Pages, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(26f) });
		GUILayout.Space(6f);
		if (page == 1)
		{
			SettingsPage();
			GUI.DragWindow(new Rect(0f, 0f, 10000f, 22f));
			return;
		}
		int num = GUILayout.Toolbar(endingIdx, EndingLabels, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		int num2 = GUILayout.Toolbar(presetIdx, PresetLabels, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		int num3 = GUILayout.Toolbar(charIdx, CharLabels, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (num != endingIdx || num2 != presetIdx || num3 != charIdx)
		{
			endingIdx = num;
			presetIdx = num2;
			charIdx = num3;
			LoadBoard();
		}
		GUILayout.Space(6f);
		if (boardStatus.Length > 0)
		{
			GUILayout.Label(boardStatus, small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		foreach (Entry entry in entries)
		{
			GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.Label("#" + entry.Rank, row, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(40f) });
			GUILayout.Label(entry.Name, row, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(200f) });
			GUILayout.Label((entry.Character >= 0 && entry.Character < 3) ? CharLabels[entry.Character + 1] : "?", row, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(90f) });
			GUILayout.Label(Time(entry.Igt), row, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			GUILayout.EndHorizontal();
		}
		GUILayout.FlexibleSpace();
		if (pending > 0)
		{
			GUILayout.Label(pending + " top run(s) waiting to be checked.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		if (myPbs.Length > 0)
		{
			GUILayout.Label(myPbs, small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		GUILayout.Label(Account.Ready ? ("Playing as " + Account.Name) : "No speedrun name yet. Make one in the main menu.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (Net.UpdateRequired)
		{
			GUILayout.Label("Update Speedrun CU to version " + Net.MinVersion + " or newer to submit runs.", bad, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (GUILayout.Button("Refresh", (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			LoadBoard();
		}
		if (GUILayout.Button("Open website", (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			Application.OpenURL("https://speedrun.smellypawz.com");
		}
		if (!Account.Ready && Account.Dismissed && (Object)(object)PlayerCamera.main == (Object)null && GUILayout.Button("Make a name", (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			Account.Dismissed = false;
		}
		if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			boardOpen = false;
		}
		GUILayout.EndHorizontal();
		GUI.DragWindow(new Rect(0f, 0f, 10000f, 22f));
	}

	private static void SettingsPage()
	{
		//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
		GUILayout.Label("TIMER", title, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		Plugin.ShowTimer.Value = GUILayout.Toggle(Plugin.ShowTimer.Value, "  Show the run timer", (GUILayoutOption[])(object)new GUILayoutOption[0]);
		Plugin.ShowSplits.Value = GUILayout.Toggle(Plugin.ShowSplits.Value, "  Show layer times under the timer", (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label("Timer position", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		Plugin.TimerCorner.Value = GUILayout.Toolbar(Mathf.Clamp(Plugin.TimerCorner.Value, 0, 3), Corners, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Space(10f);
		GUILayout.Label("KEYS", title, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.Label("Open this window", row, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(160f) });
		if (GUILayout.Button(WaitingKey ? "Press a key... (Esc cancels)" : ((object)Plugin.BoardKey.Value).ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(220f) }))
		{
			WaitingKey = !WaitingKey;
		}
		GUILayout.EndHorizontal();
		GUILayout.Space(10f);
		GUILayout.Label("ACCOUNT", title, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (Account.Ready)
		{
			GUILayout.Label("Playing as " + Account.Name + ". You're logged in automatically on this PC.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if (Guard.Whitelisted)
			{
				GUILayout.Label("Whitelisted: cheats are allowed, and runs with cheats are saved as test runs.", good, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			}
			GUILayout.Label("Your login is in BepInEx\\config\\speedruncu.account. Back it up, and never share it.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		}
		else
		{
			GUILayout.Label("No speedrun name yet.", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
			if ((Object)(object)PlayerCamera.main == (Object)null && GUILayout.Button("Make a name", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(140f) }))
			{
				Account.Dismissed = false;
				boardOpen = false;
			}
		}
		GUILayout.FlexibleSpace();
		GUILayout.Label("Speedrun CU 1.0.0  ·  settings save automatically", small, (GUILayoutOption[])(object)new GUILayoutOption[0]);
		GUILayout.BeginHorizontal((GUILayoutOption[])(object)new GUILayoutOption[0]);
		if (GUILayout.Button("Open website", (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			Application.OpenURL("https://speedrun.smellypawz.com");
		}
		if (GUILayout.Button("Close", (GUILayoutOption[])(object)new GUILayoutOption[0]))
		{
			boardOpen = false;
			WaitingKey = false;
		}
		GUILayout.EndHorizontal();
	}
}