Decompiled source of SBGL LiveLeaderboard v0.0.92

SBGL-LiveLeaderboard.dll

Decompiled 2 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: IgnoresAccessChecksTo("GameAssembly")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SBGL-LiveLeaderboard")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0+9a171ae398e246e91e136508c15c434c7e536a35")]
[assembly: AssemblyProduct("Super Battle Golf League Live Leaderboard")]
[assembly: AssemblyTitle("SBGL-LiveLeaderboard")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SBGLLiveLeaderboard
{
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "SBGL-LiveLeaderboard";

		public const string PLUGIN_NAME = "Super Battle Golf League Live Leaderboard";

		public const string PLUGIN_VERSION = "0.0.0";
	}
}
namespace SBGLiveLeaderboard
{
	[BepInPlugin("com.kingcox22.sbgl.liveleaderboard", "SBGL Live Leaderboard", "2.7.0")]
	public class LiveLeaderboardPlugin : BaseUnityPlugin
	{
		public class SBGLPlayer
		{
			public string Name;

			public int BaseScore;

			public int AdjustedPoints;

			public string RawStrokes;

			public string MMR = "...";
		}

		[CompilerGenerated]
		private sealed class <GetMMRForPlayer>d__29 : IEnumerator<object>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private object <>2__current;

			public string originalName;

			public LiveLeaderboardPlugin <>4__this;

			private string <lookupName>5__1;

			private string <query>5__2;

			private string <url>5__3;

			private UnityWebRequest <r>5__4;

			private JArray <res>5__5;

			object IEnumerator<object>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetMMRForPlayer>d__29(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<lookupName>5__1 = null;
				<query>5__2 = null;
				<url>5__3 = null;
				<r>5__4 = null;
				<res>5__5 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_012e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0134: Invalid comparison between Unknown and I4
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<lookupName>5__1 = ((originalName == "KingCox22") ? "Khaz" : originalName);
						if (<>4__this._pendingRequests.Contains(<lookupName>5__1))
						{
							return false;
						}
						<>4__this._pendingRequests.Add(<lookupName>5__1);
						<query>5__2 = "{\"display_name\":\"" + <lookupName>5__1 + "\"}";
						<url>5__3 = "https://sbgleague.com/api/apps/69b0f4aba3975f2440fbf070/entities/Player?q=" + UnityWebRequest.EscapeURL(<query>5__2);
						<r>5__4 = UnityWebRequest.Get(<url>5__3);
						<>1__state = -3;
						<r>5__4.SetRequestHeader("X-App-Id", "69b0f4aba3975f2440fbf070");
						<r>5__4.SetRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJraW5nY294MjJAZ21haWwuY29tIiwiZXhwIjoxNzgyNzg5NDU0LCJpYXQiOjE3NzUwMTM0NTR9.2pCmAKXH98n3fvUaheN-e6kx3BoJflStfUb-Kq-i-gU");
						<>2__current = <r>5__4.SendWebRequest();
						<>1__state = 1;
						return true;
					case 1:
						<>1__state = -3;
						if ((int)<r>5__4.result == 1)
						{
							try
							{
								<res>5__5 = JArray.Parse(<r>5__4.downloadHandler.text);
								<>4__this._mmrCache[originalName] = ((((JContainer)<res>5__5).Count <= 0) ? "N/A" : (((object)<res>5__5[0][(object)"current_mmr"])?.ToString() ?? "0"));
								<res>5__5 = null;
							}
							catch
							{
								<>4__this._mmrCache[originalName] = "ERR";
							}
						}
						else
						{
							<>4__this._mmrCache[originalName] = "OFF";
						}
						<>m__Finally1();
						<r>5__4 = null;
						<>4__this._pendingRequests.Remove(<lookupName>5__1);
						return false;
					}
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<r>5__4 != null)
				{
					((IDisposable)<r>5__4).Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private const string APP_ID = "69b0f4aba3975f2440fbf070";

		private const string AUTH_TOKEN = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJraW5nY294MjJAZ21haWwuY29tIiwiZXhwIjoxNzgyNzg5NDU0LCJpYXQiOjE3NzUwMTM0NTR9.2pCmAKXH98n3fvUaheN-e6kx3BoJflStfUb-Kq-i-gU";

		private const string BASE_API = "https://sbgleague.com/api/apps/69b0f4aba3975f2440fbf070/entities/Player";

		public ConfigEntry<float> ConfigWidth;

		public ConfigEntry<float> ConfigMaxHeight;

		public ConfigEntry<float> ConfigPosX;

		public ConfigEntry<float> ConfigPosY;

		public ConfigEntry<float> ConfigOpacity;

		public ConfigEntry<Key> ToggleKey;

		private bool _showWindow = true;

		private Rect _windowRect = new Rect(3f, 140f, 260f, 50f);

		private float _updateInterval = 2f;

		private float _nextUpdateTime = 0f;

		private float _lastOpacity = -1f;

		private List<SBGLPlayer> _persistentLeaderboard = new List<SBGLPlayer>();

		private Dictionary<string, string> _mmrCache = new Dictionary<string, string>();

		private HashSet<string> _pendingRequests = new HashSet<string>();

		private FieldInfo _entriesField;

		private Scoreboard _cachedScoreboard;

		private GUIStyle _windowStyle;

		private Texture2D _blackTexture;

		private void Awake()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0078: Expected O, but got Unknown
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: Expected O, but got Unknown
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			ConfigWidth = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "Width", 260f, new ConfigDescription("Width of the window.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(150f, 800f), Array.Empty<object>()));
			ConfigMaxHeight = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "Max Height", 999f, new ConfigDescription("Max height.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(100f, 2000f), Array.Empty<object>()));
			ConfigPosX = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "X Position", 3f, new ConfigDescription("Left/Right.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 4000f), Array.Empty<object>()));
			ConfigPosY = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "Y Position", 140f, new ConfigDescription("Up/Down.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 4000f), Array.Empty<object>()));
			ConfigOpacity = ((BaseUnityPlugin)this).Config.Bind<float>("UI", "Opacity", 0.75f, new ConfigDescription("Alpha", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
			ToggleKey = ((BaseUnityPlugin)this).Config.Bind<Key>("Controls", "Toggle Key", (Key)101, "Hotkey to hide/show.");
			_entriesField = typeof(Scoreboard).GetField("entries", BindingFlags.Instance | BindingFlags.NonPublic);
			_blackTexture = new Texture2D(1, 1);
			UpdateTextureOpacity();
			((Rect)(ref _windowRect)).x = ConfigPosX.Value;
			((Rect)(ref _windowRect)).y = ConfigPosY.Value;
			((Rect)(ref _windowRect)).width = ConfigWidth.Value;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
		}

		private void UpdateTextureOpacity()
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			_blackTexture.SetPixel(0, 0, new Color(0f, 0f, 0f, ConfigOpacity.Value));
			_blackTexture.Apply();
			_lastOpacity = ConfigOpacity.Value;
		}

		private void Update()
		{
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: 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)
			((Rect)(ref _windowRect)).x = ConfigPosX.Value;
			((Rect)(ref _windowRect)).y = ConfigPosY.Value;
			((Rect)(ref _windowRect)).width = ConfigWidth.Value;
			if (Keyboard.current != null && ((ButtonControl)Keyboard.current[ToggleKey.Value]).wasPressedThisFrame)
			{
				_showWindow = !_showWindow;
			}
			if ((Object)(object)_cachedScoreboard == (Object)null)
			{
				_cachedScoreboard = Object.FindAnyObjectByType<Scoreboard>((FindObjectsInactive)1);
			}
			Scene activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name.Contains("Driving"))
			{
				return;
			}
			activeScene = SceneManager.GetActiveScene();
			if (((Scene)(ref activeScene)).name.Contains("Range"))
			{
				return;
			}
			if (Time.time >= _nextUpdateTime)
			{
				ScrapeData();
				_nextUpdateTime = Time.time + _updateInterval;
			}
			if ((Object)(object)_cachedScoreboard != (Object)null && !((Component)_cachedScoreboard).gameObject.activeSelf)
			{
				((Component)_cachedScoreboard).gameObject.SetActive(true);
				CanvasGroup component = ((Component)_cachedScoreboard).GetComponent<CanvasGroup>();
				if ((Object)(object)component != (Object)null)
				{
					component.alpha = 0f;
				}
			}
		}

		private void OnGUI()
		{
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			if (_showWindow)
			{
				GUI.depth = -1000;
				if (Mathf.Abs(_lastOpacity - ConfigOpacity.Value) > 0.01f)
				{
					UpdateTextureOpacity();
				}
				if (_windowStyle == null)
				{
					_windowStyle = new GUIStyle(GUI.skin.window);
					_windowStyle.normal.background = _blackTexture;
					_windowStyle.focused.background = _blackTexture;
					_windowStyle.onNormal.background = _blackTexture;
				}
				float num = 85f + (float)_persistentLeaderboard.Count * 33f;
				((Rect)(ref _windowRect)).height = Mathf.Min(num, ConfigMaxHeight.Value);
				_windowRect = GUILayout.Window(22, _windowRect, new WindowFunction(DrawLeaderboardWindow), "SBGL Live Leaderboard", _windowStyle, Array.Empty<GUILayoutOption>());
				if (ConfigPosX.Value != ((Rect)(ref _windowRect)).x)
				{
					ConfigPosX.Value = ((Rect)(ref _windowRect)).x;
				}
				if (ConfigPosY.Value != ((Rect)(ref _windowRect)).y)
				{
					ConfigPosY.Value = ((Rect)(ref _windowRect)).y;
				}
			}
		}

		private void DrawLeaderboardWindow(int windowID)
		{
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			GUILayout.BeginVertical(Array.Empty<GUILayoutOption>());
			float num = ((Rect)(ref _windowRect)).width * 0.1f;
			float num2 = ((Rect)(ref _windowRect)).width * 0.3f;
			float num3 = ((Rect)(ref _windowRect)).width * 0.15f;
			float num4 = ((Rect)(ref _windowRect)).width * 0.15f;
			float num5 = ((Rect)(ref _windowRect)).width * 0.15f;
			float num6 = ((Rect)(ref _windowRect)).width * 0.15f;
			GUILayout.BeginHorizontal(GUIStyle.op_Implicit("box"), Array.Empty<GUILayoutOption>());
			GUILayout.Label("<b>#</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num) });
			GUILayout.Label("<b>Player</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num2) });
			GUILayout.Label("<b>MMR</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num3) });
			GUILayout.Label("<b>SBGL</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num4) });
			GUILayout.Label("<b>+/-</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num5) });
			GUILayout.Label("<b>Base</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num6) });
			GUILayout.EndHorizontal();
			if (_persistentLeaderboard.Count == 0)
			{
				GUILayout.Label("<color=#888888>Waiting for match data...</color>", Array.Empty<GUILayoutOption>());
			}
			else
			{
				for (int i = 0; i < _persistentLeaderboard.Count; i++)
				{
					SBGLPlayer sBGLPlayer = _persistentLeaderboard[i];
					GUILayout.BeginHorizontal(GUIStyle.op_Implicit("box"), Array.Empty<GUILayoutOption>());
					string text = (sBGLPlayer.Name.Contains("KingCox22") ? "<color=yellow>" : "<color=white>");
					GUILayout.Label("<color=#00FF00>" + GetOrdinal(i + 1) + "</color>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num) });
					GUILayout.Label(text + sBGLPlayer.Name + "</color>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num2) });
					GUILayout.Label("<color=#00FFFF>" + sBGLPlayer.MMR + "</color>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num3) });
					GUILayout.Label($"<b>{sBGLPlayer.AdjustedPoints}</b>", (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num4) });
					GUILayout.Label(sBGLPlayer.RawStrokes, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num5) });
					GUILayout.Label(sBGLPlayer.BaseScore.ToString(), (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Width(num6) });
					GUILayout.EndHorizontal();
				}
			}
			GUILayout.FlexibleSpace();
			GUILayout.Label($"<size=10><color=#888888>Toggle: {ToggleKey.Value} | Drag to Move</color></size>", Array.Empty<GUILayoutOption>());
			GUILayout.EndVertical();
			GUI.DragWindow();
		}

		private void ScrapeData()
		{
			if ((Object)(object)_cachedScoreboard == (Object)null || _entriesField == null || !(_entriesField.GetValue(_cachedScoreboard) is List<ScoreboardEntry> list) || list.Count == 0)
			{
				return;
			}
			List<SBGLPlayer> list2 = new List<SBGLPlayer>();
			foreach (ScoreboardEntry item in list)
			{
				if ((Object)(object)item == (Object)null)
				{
					continue;
				}
				TextMeshProUGUI name = item.name;
				string text = CleanTMP((name != null) ? ((TMP_Text)name).text : null);
				if (string.IsNullOrEmpty(text) || text == "Name" || text.ToLower().Contains("spectator"))
				{
					continue;
				}
				TextMeshProUGUI strokes = item.strokes;
				string text2 = CleanTMP((strokes != null) ? ((TMP_Text)strokes).text : null);
				if (!string.IsNullOrEmpty(text2) && !text2.ToUpper().Contains("SPEC"))
				{
					TextMeshProUGUI courseScore = item.courseScore;
					int.TryParse(CleanTMP((courseScore != null) ? ((TMP_Text)courseScore).text : null), out var result);
					int.TryParse(text2.Replace("±", "").Replace("+", "").Trim(), out var result2);
					string text3 = (_mmrCache.ContainsKey(text) ? _mmrCache[text] : "...");
					if (text3 == "...")
					{
						((MonoBehaviour)this).StartCoroutine(GetMMRForPlayer(text));
					}
					list2.Add(new SBGLPlayer
					{
						Name = text,
						BaseScore = result,
						RawStrokes = text2,
						AdjustedPoints = result + result2 * -10,
						MMR = text3
					});
				}
			}
			if (list2.Count > 0)
			{
				_persistentLeaderboard = list2.OrderByDescending((SBGLPlayer p) => p.AdjustedPoints).ToList();
			}
		}

		private string GetOrdinal(int num)
		{
			if (num <= 0)
			{
				return num.ToString();
			}
			int num2 = num % 100;
			int num3 = num2;
			if ((uint)(num3 - 11) <= 2u)
			{
				return num + "th";
			}
			return (num % 10) switch
			{
				1 => num + "st", 
				2 => num + "nd", 
				3 => num + "rd", 
				_ => num + "th", 
			};
		}

		[IteratorStateMachine(typeof(<GetMMRForPlayer>d__29))]
		private IEnumerator GetMMRForPlayer(string originalName)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetMMRForPlayer>d__29(0)
			{
				<>4__this = this,
				originalName = originalName
			};
		}

		private string CleanTMP(string input)
		{
			return string.IsNullOrEmpty(input) ? "" : Regex.Replace(input, "<.*?>", string.Empty).Trim();
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}