Decompiled source of SilentVanillaVote v1.0.2

SilentVanillaVote.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Photon.Pun;
using Photon.Realtime;
using SVVote.Voting;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Silent")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2")]
[assembly: AssemblyProduct("SilentVanilla Vote")]
[assembly: AssemblyTitle("SilentVanillaVote")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.0")]
[module: UnverifiableCode]
namespace SVVote
{
	[BepInPlugin("silent.vanilla.vote", "SilentVanilla Vote", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		internal static Plugin Instance;

		internal static ManualLogSource Log;

		internal ConfigEntry<bool> VotingEnabled;

		internal ConfigEntry<bool> DebugLog;

		private Harmony harmony;

		internal static bool IsHost
		{
			get
			{
				try
				{
					return SemiFunc.IsMasterClientOrSingleplayer();
				}
				catch (Exception)
				{
					return false;
				}
			}
		}

		internal static bool VotingActive
		{
			get
			{
				Plugin instance = Instance;
				if (!((Object)(object)instance == (Object)null) && instance.VotingEnabled != null)
				{
					return instance.VotingEnabled.Value;
				}
				return true;
			}
		}

		internal static bool DebugEnabled
		{
			get
			{
				Plugin instance = Instance;
				if ((Object)(object)instance != (Object)null && instance.DebugLog != null)
				{
					return instance.DebugLog.Value;
				}
				return false;
			}
		}

		private void Awake()
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			VotingEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Voting", "Enabled", true, "Host-side master switch for chat voting. Set to false to disable the whole feature.");
			DebugLog = ((BaseUnityPlugin)this).Config.Bind<bool>("Voting", "DebugLog", false, "Verbose logging of incoming votes and vote application.");
			TaxmanQuietStart.QuietSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Taxman", "QuietSeconds", 15f, "Seconds the vanilla Taxman's scripted pages stay invisible at the start of every phase (level, store, truck). The pages still type and drive the game normally; only their text is muted so the vote list shows first. 0 disables muting.");
			harmony = new Harmony("silent.vanilla.vote");
			harmony.PatchAll();
			SVPresentation.Install();
			Log.LogInfo((object)"SilentVanilla Vote 1.0.2 loaded (host-only, votes in the truck phase)");
		}

		private void OnDestroy()
		{
			Harmony obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
		}
	}
	internal static class SVPresentation
	{
		internal const int UID = 3;

		private static readonly string[] SeriesGUIDs = new string[3] { "silent.vanilla", "silent.vanilla.maps", "silent.vanilla.vote" };

		internal const string MarkerName = "SV_PresentationMarker";

		private const float ScreenWaitMax = 20f;

		private const float SettleSeconds = 3f;

		private const float TypingWaitMax = 10f;

		private static bool ownsMarker;

		private const string ThisModName = "SilentVanilla Vote";

		internal static bool WouldShow()
		{
			return Plugin.IsHost;
		}

		private static bool Installed(string guid)
		{
			try
			{
				PluginInfo value;
				return Chainloader.PluginInfos.TryGetValue(guid, out value) && value != null && (Object)(object)value.Instance != (Object)null;
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static bool Outranked()
		{
			for (int i = 0; i < SeriesGUIDs.Length && i + 1 < 3; i++)
			{
				if (Installed(SeriesGUIDs[i]))
				{
					return true;
				}
			}
			return false;
		}

		internal static void Install()
		{
			SceneManager.sceneLoaded += OnSceneLoaded;
		}

		private static void OnSceneLoaded(Scene scene, LoadSceneMode mode)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			if ((int)mode == 0 && !((Object)(object)Plugin.Instance == (Object)null))
			{
				((MonoBehaviour)Plugin.Instance).StartCoroutine(Show());
			}
		}

		private static IEnumerator Show()
		{
			bool flag = (Object)(object)GameObject.Find("SV_PresentationMarker") != (Object)null;
			if (flag && !ownsMarker)
			{
				yield break;
			}
			if (!flag)
			{
				if (!WouldShow() || Outranked())
				{
					yield break;
				}
				Object.DontDestroyOnLoad((Object)new GameObject("SV_PresentationMarker"));
				ownsMarker = true;
			}
			float waited = 0f;
			while ((Object)(object)TruckScreenText.instance == (Object)null && waited < 20f)
			{
				waited += Time.deltaTime;
				yield return null;
			}
			if (!((Object)(object)TruckScreenText.instance == (Object)null))
			{
				yield return (object)new WaitForSeconds(3f);
				waited = 0f;
				while (VoteScreen.IsTyping() && waited < 10f)
				{
					waited += Time.deltaTime;
					yield return null;
				}
				List<string> list = SeriesMods();
				Say(Message(list));
				if (Plugin.DebugEnabled)
				{
					Plugin.Log.LogInfo((object)("Taxman presentation shown after settle. Series mods installed: " + string.Join(", ", list)));
				}
			}
		}

		private static string Message(List<string> mods)
		{
			List<string> list = new List<string>();
			for (int i = 0; i < mods.Count; i++)
			{
				list.Add("<color=#00FF00>» " + mods[i] + "</color>");
			}
			return "<b>==========  SILENT VANILLA MODS  ==========</b>\n" + string.Join("\n", list.ToArray());
		}

		private static List<string> SeriesMods()
		{
			List<string> list = new List<string>();
			try
			{
				foreach (PluginInfo value in Chainloader.PluginInfos.Values)
				{
					if (value != null && value.Metadata != null && !string.IsNullOrEmpty(value.Metadata.GUID) && value.Metadata.GUID.StartsWith("silent.vanilla", StringComparison.OrdinalIgnoreCase) && !((Object)(object)value.Instance == (Object)null))
					{
						list.Add(value.Metadata.Name);
					}
				}
			}
			catch (Exception ex)
			{
				if (Plugin.DebugEnabled)
				{
					Plugin.Log.LogWarning((object)("Series discovery failed; showing this mod only\n" + ex));
				}
			}
			if (list.Count == 0)
			{
				list.Add("SilentVanilla Vote");
			}
			list.Sort(StringComparer.OrdinalIgnoreCase);
			return list;
		}

		private static void Say(string text)
		{
			try
			{
				TruckScreenText instance = TruckScreenText.instance;
				if ((Object)(object)instance != (Object)null)
				{
					instance.MessageSendCustom(string.Empty, text, 0);
				}
			}
			catch (Exception ex)
			{
				if (Plugin.DebugEnabled)
				{
					Plugin.Log.LogWarning((object)("Presentation page failed\n" + ex));
				}
			}
		}
	}
}
namespace SVVote.Voting
{
	internal static class MapsBridge
	{
		internal const string MapsGuid = "silent.vanilla.maps";

		internal static readonly string[] ModeNames = new string[5] { "Vanilla", "AllRandom", "Districts", "LongRun", "Stairs" };

		internal static readonly string[] ModeLabels = new string[5] { "Default Vanilla", "All Random", "Districts", "Long Run", "Stairs" };

		private const string MuseumLevelNameKeyword = "museum";

		private static bool resolved;

		private static Type enumType;

		private static FieldInfo modesByLevelField;

		internal static bool Installed
		{
			get
			{
				try
				{
					PluginInfo value;
					return Chainloader.PluginInfos.TryGetValue("silent.vanilla.maps", out value) && value != null && (Object)(object)value.Instance != (Object)null;
				}
				catch (Exception)
				{
					return false;
				}
			}
		}

		internal static bool TrySetMode(Level level, string modeName)
		{
			if ((Object)(object)level == (Object)null || string.IsNullOrEmpty(modeName))
			{
				return false;
			}
			if (!Resolve())
			{
				return false;
			}
			try
			{
				object obj = Enum.Parse(enumType, modeName, ignoreCase: false);
				if (modesByLevelField.GetValue(null) is IDictionary dictionary && obj != null)
				{
					dictionary[level] = obj;
					return true;
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not write the vote into Maps\n" + ex));
			}
			return false;
		}

		internal static Level FindMuseumLevel()
		{
			RunManager instance;
			try
			{
				instance = RunManager.instance;
			}
			catch (Exception)
			{
				return null;
			}
			if ((Object)(object)instance == (Object)null || instance.levels == null)
			{
				return null;
			}
			for (int i = 0; i < instance.levels.Count; i++)
			{
				Level val = instance.levels[i];
				if (!((Object)(object)val == (Object)null) && ((((Object)val).name != null && ((Object)val).name.IndexOf("museum", StringComparison.OrdinalIgnoreCase) >= 0) || (val.NarrativeName != null && val.NarrativeName.IndexOf("museum", StringComparison.OrdinalIgnoreCase) >= 0)))
				{
					return val;
				}
			}
			return null;
		}

		private static bool Resolve()
		{
			if (resolved)
			{
				if (enumType != null)
				{
					return modesByLevelField != null;
				}
				return false;
			}
			resolved = true;
			try
			{
				if (!Chainloader.PluginInfos.TryGetValue("silent.vanilla.maps", out var value) || value == null)
				{
					return false;
				}
				Type type = null;
				if ((Object)(object)value.Instance != (Object)null)
				{
					type = ((object)value.Instance).GetType().Assembly.GetType("SVMaps.Plugin");
				}
				if (type == null)
				{
					return false;
				}
				enumType = type.GetNestedType("SVMapMode", BindingFlags.Public | BindingFlags.NonPublic);
				modesByLevelField = type.GetField("ModesByLevel", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (enumType == null)
				{
					Plugin.Log.LogWarning((object)"SilentVanilla Maps detected but its map-mode enum was not found");
					return false;
				}
				if (modesByLevelField == null)
				{
					Plugin.Log.LogWarning((object)"SilentVanilla Maps detected but its mode registry was not found");
					return false;
				}
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("SilentVanilla Maps bridge failed to resolve\n" + ex));
				return false;
			}
		}
	}
	internal static class TaxmanQuietStart
	{
		internal static ConfigEntry<float> QuietSeconds;

		internal static bool SuppressActive()
		{
			try
			{
				if (QuietSeconds == null || QuietSeconds.Value <= 0f)
				{
					return false;
				}
				return Time.timeSinceLevelLoad < QuietSeconds.Value;
			}
			catch (Exception)
			{
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(TruckScreenText), "InitializeTextTyping")]
	internal static class Patch_TaxmanIntroSilencer
	{
		private static readonly MethodInfo Logic = AccessTools.Method(typeof(TruckScreenText), "InitializeTextTypingLogic", (Type[])null, (Type[])null);

		private static bool Prefix(TruckScreenText __instance)
		{
			if (!TaxmanQuietStart.SuppressActive())
			{
				return true;
			}
			try
			{
				Logic?.Invoke(__instance, null);
			}
			catch (Exception)
			{
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(TruckScreenText), "TypingUpdate")]
	internal static class Patch_TaxmanMuteTyping
	{
		private static TruckScreenText muteScreen;

		private static int muteLength = -1;

		private static void Prefix(TruckScreenText __instance)
		{
			muteScreen = null;
			muteLength = -1;
			if (!TaxmanQuietStart.SuppressActive())
			{
				return;
			}
			muteScreen = __instance;
			try
			{
				muteLength = ((TMP_Text)__instance.textMesh).text.Length;
			}
			catch (Exception)
			{
				muteLength = -1;
			}
		}

		private static void Postfix(TruckScreenText __instance)
		{
			if ((Object)(object)muteScreen != (Object)(object)__instance || muteLength < 0)
			{
				return;
			}
			try
			{
				if (((TMP_Text)__instance.textMesh).text.Length > muteLength)
				{
					((TMP_Text)__instance.textMesh).text = ((TMP_Text)__instance.textMesh).text.Substring(0, muteLength);
				}
			}
			catch (Exception)
			{
			}
		}
	}
	internal static class TaxmanSay
	{
		internal static bool Say(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return false;
			}
			TruckScreenText instance;
			try
			{
				instance = TruckScreenText.instance;
			}
			catch (Exception)
			{
				return false;
			}
			if ((Object)(object)instance == (Object)null)
			{
				return false;
			}
			try
			{
				instance.MessageSendCustom(string.Empty, text, 0);
				Plugin.Log.LogInfo((object)("[SilentVanillaVote] truck screen page sent (" + text.Split('\n')[0] + ")"));
				return true;
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("Truck screen message failed\n" + ex2));
				return false;
			}
		}
	}
	internal static class VoteScreen
	{
		private const float ScreenWaitMax = 20f;

		private const float TypingWaitMax = 10f;

		private const float PageGap = 1.5f;

		private static readonly Queue<string> pages = new Queue<string>();

		private static bool pumping;

		private static readonly FieldInfo IsTypingField = typeof(TruckScreenText).GetField("isTyping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

		internal static void Enqueue(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return;
			}
			Plugin instance = Plugin.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				pages.Enqueue(text);
				if (!pumping)
				{
					pumping = true;
					((MonoBehaviour)instance).StartCoroutine(Pump());
				}
			}
		}

		private static IEnumerator Pump()
		{
			try
			{
				while (pages.Count > 0)
				{
					string page = pages.Dequeue();
					bool sent = false;
					float waited = 0f;
					while ((Object)(object)TruckScreenText.instance == (Object)null && waited < 20f)
					{
						waited += Time.deltaTime;
						yield return null;
					}
					if ((Object)(object)TruckScreenText.instance != (Object)null)
					{
						if (!TaxmanQuietStart.SuppressActive())
						{
							waited = 0f;
							while (IsTyping() && waited < 10f)
							{
								waited += Time.deltaTime;
								yield return null;
							}
							if (IsTyping())
							{
								if (Plugin.DebugEnabled)
								{
									Plugin.Log.LogWarning((object)("Vote page dropped (screen stuck typing): " + FirstLine(page)));
								}
								continue;
							}
						}
						TaxmanSay.Say(page);
						sent = true;
						yield return (object)new WaitForSeconds(1.5f);
					}
					if (!sent && Plugin.DebugEnabled)
					{
						Plugin.Log.LogWarning((object)("Vote page dropped (no screen or screen stuck typing): " + FirstLine(page)));
					}
				}
			}
			finally
			{
				pumping = false;
			}
		}

		internal static bool IsTyping()
		{
			if (IsTypingField == null)
			{
				return false;
			}
			try
			{
				TruckScreenText instance = TruckScreenText.instance;
				if ((Object)(object)instance == (Object)null)
				{
					return false;
				}
				return (bool)IsTypingField.GetValue(instance);
			}
			catch (Exception)
			{
				return false;
			}
		}

		private static string FirstLine(string page)
		{
			int num = page.IndexOf('\n');
			if (num >= 0)
			{
				return page.Substring(0, num);
			}
			return page;
		}
	}
	internal static class VoteService
	{
		private static bool lobbyPhase;

		private static bool usingMaps;

		private static List<Level> ballotLevels;

		private static int ballotSize;

		private static readonly Dictionary<Player, int> Votes = new Dictionary<Player, int>();

		internal static void SyncPhase(bool lobbyNow)
		{
			if (lobbyNow && !lobbyPhase)
			{
				OpenWindow();
			}
			lobbyPhase = lobbyNow;
		}

		private static void EnsurePhase()
		{
			try
			{
				SyncPhase(SemiFunc.RunIsLobby());
			}
			catch (Exception)
			{
			}
		}

		private static void OpenWindow()
		{
			Votes.Clear();
			ballotLevels = null;
			ballotSize = 0;
			usingMaps = MapsBridge.Installed;
			if (usingMaps)
			{
				ballotSize = MapsBridge.ModeLabels.Length;
			}
			else
			{
				List<Level> list = SafeGameLevels();
				if (list != null && list.Count > 0)
				{
					ballotLevels = list;
					ballotSize = list.Count;
				}
			}
			if (ballotSize > 0)
			{
				VoteScreen.Enqueue(BuildBallotPage());
			}
			if (Plugin.DebugEnabled)
			{
				Plugin.Log.LogInfo((object)("[SilentVanillaVote] Truck vote window open: " + KindDescription() + ", options " + ballotSize));
			}
		}

		private static string KindDescription()
		{
			if (!usingMaps)
			{
				return "the game's own levels";
			}
			return "custom map modes";
		}

		internal static bool HandleChat(string message, PhotonMessageInfo info)
		{
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.VotingActive)
			{
				return false;
			}
			string text = message?.Trim();
			if (string.IsNullOrEmpty(text) || text.Length < 2 || text[0] != '!')
			{
				return false;
			}
			string[] array = text.Substring(1).Split(' ');
			if (array.Length == 0 || array[0] == null || !array[0].Equals("vote", StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			Player val = ReadSender(info);
			string text2 = Sanitize(SafeNick(val));
			bool flag;
			try
			{
				flag = SemiFunc.RunIsLobby();
			}
			catch (Exception)
			{
				flag = false;
			}
			if (!flag)
			{
				if (Plugin.DebugEnabled)
				{
					Plugin.Log.LogInfo((object)("[SilentVanillaVote] Vote from " + text2 + " ignored (not in the truck)"));
				}
				return true;
			}
			EnsurePhase();
			if (ballotSize == 0)
			{
				VoteScreen.Enqueue("There is nothing to vote for right now");
				return true;
			}
			if (array.Length == 1)
			{
				VoteScreen.Enqueue(BuildBallotPage());
				return true;
			}
			if (!int.TryParse(array[1], out var result) || result < 1 || result > ballotSize)
			{
				VoteScreen.Enqueue(Sanitize(array[1]) + " is not a map number (1 to " + ballotSize + ")");
				return true;
			}
			if (val != null)
			{
				Votes[val] = result;
			}
			if (Plugin.DebugEnabled)
			{
				int count = Votes.Count;
				int num = CountFor(result - 1);
				Plugin.Log.LogInfo((object)("[SilentVanillaVote] " + text2 + " voted for option " + result + " (" + num + " vote" + ((num == 1) ? "" : "s") + ", " + count + " player" + ((count == 1) ? "" : "s") + " voted)"));
			}
			VoteScreen.Enqueue(BuildBallotPage() + "\n" + text2 + " chose: " + LabelFor(result - 1));
			return true;
		}

		internal static bool TryForcePendingLevel(RunManager manager)
		{
			if ((Object)(object)manager == (Object)null || MapsBridge.Installed || !HasPendingVotes())
			{
				return true;
			}
			if (manager.levels == null || manager.levels.Count == 0)
			{
				return true;
			}
			int num = TallyWinner();
			if (num < 0)
			{
				CloseWindow();
				return true;
			}
			if (usingMaps || ballotLevels == null)
			{
				CloseWindow();
				return true;
			}
			Level val = ballotLevels[num];
			if ((Object)(object)val == (Object)null)
			{
				CloseWindow();
				return true;
			}
			int voteCount = CountFor(num);
			string text = LabelFor(num);
			CloseWindow();
			manager.levelCurrent = val;
			if (Plugin.DebugEnabled)
			{
				Plugin.Log.LogInfo((object)("[SilentVanillaVote] Vote applied: " + text + " (" + voteCount + " votes) - vanilla random pick skipped"));
			}
			VoteScreen.Enqueue(BuildResultPage(text, voteCount));
			return false;
		}

		internal static void ApplyMapsModeVote(RunManager manager)
		{
			if ((Object)(object)manager == (Object)null || !HasPendingVotes())
			{
				return;
			}
			int num = TallyWinner();
			if (num < 0)
			{
				CloseWindow();
				return;
			}
			usingMaps = true;
			string text = LabelFor(num);
			string modeName = MapsBridge.ModeNames[num];
			int voteCount = CountFor(num);
			bool flag = false;
			if (num == 0)
			{
				flag = MapsBridge.TrySetMode(manager.levelCurrent, modeName);
			}
			else
			{
				Level val = MapsBridge.FindMuseumLevel();
				if ((Object)(object)val != (Object)null)
				{
					manager.levelCurrent = val;
					flag = MapsBridge.TrySetMode(val, modeName);
				}
			}
			CloseWindow();
			if (Plugin.DebugEnabled)
			{
				Plugin.Log.LogInfo((object)("[SilentVanillaVote] Vote applied: " + text + " (" + voteCount + " votes), bridge " + (flag ? "OK" : "FAILED")));
			}
			VoteScreen.Enqueue(BuildResultPage(text, voteCount));
		}

		private static bool HasPendingVotes()
		{
			return Votes.Count > 0;
		}

		private static int TallyWinner()
		{
			int result = -1;
			int num = 0;
			for (int i = 0; i < ballotSize; i++)
			{
				int num2 = CountFor(i);
				if (num2 > num)
				{
					result = i;
					num = num2;
				}
			}
			if (Votes.Count <= 0)
			{
				return -1;
			}
			return result;
		}

		private static int CountFor(int optionIndex)
		{
			if (optionIndex < 0 || optionIndex >= ballotSize)
			{
				return 0;
			}
			int num = 0;
			foreach (int value in Votes.Values)
			{
				if (value - 1 == optionIndex)
				{
					num++;
				}
			}
			return num;
		}

		private static void CloseWindow()
		{
			Votes.Clear();
			ballotLevels = null;
			ballotSize = 0;
		}

		private static string BuildBallotPage()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("<b>MAP VOTE</b>");
			for (int i = 0; i < ballotSize; i++)
			{
				int num = CountFor(i);
				stringBuilder.Append('\n').Append(i + 1).Append(". ")
					.Append(LabelFor(i));
				if (Votes.Count > 0)
				{
					stringBuilder.Append(" - ").Append(num).Append(" vote")
						.Append((num == 1) ? "" : "s");
				}
			}
			if (Votes.Count > 0)
			{
				stringBuilder.Append("\n").Append(Votes.Count).Append(" of ")
					.Append(SemiFunc.PlayerGetList().Count)
					.Append(" players voted");
			}
			stringBuilder.Append("\nType !vote number in chat");
			return stringBuilder.ToString();
		}

		private static string BuildResultPage(string winnerLabel, int voteCount)
		{
			return BuildBallotPage() + "\n<b>WINNER: " + winnerLabel + "</b> (" + voteCount + ((voteCount == 1) ? " vote)" : " votes)");
		}

		private static string LabelFor(int index)
		{
			if (index < 0)
			{
				return "?";
			}
			if (usingMaps)
			{
				if (index >= MapsBridge.ModeLabels.Length)
				{
					return "?";
				}
				return MapsBridge.ModeLabels[index];
			}
			if (ballotLevels != null && index < ballotLevels.Count)
			{
				return SafeLevelName(ballotLevels[index]);
			}
			return "?";
		}

		private static List<Level> SafeGameLevels()
		{
			try
			{
				RunManager instance = RunManager.instance;
				if ((Object)(object)instance != (Object)null && instance.levels != null && instance.levels.Count > 0)
				{
					List<Level> list = new List<Level>();
					for (int i = 0; i < instance.levels.Count; i++)
					{
						Level val = instance.levels[i];
						if ((Object)(object)val != (Object)null)
						{
							list.Add(val);
						}
					}
					return list;
				}
			}
			catch (Exception)
			{
			}
			return null;
		}

		private static string SafeLevelName(Level level)
		{
			try
			{
				if (!string.IsNullOrEmpty(((Object)level).name))
				{
					return Sanitize(((Object)level).name);
				}
				if (!string.IsNullOrEmpty(level.NarrativeName))
				{
					return Sanitize(level.NarrativeName);
				}
			}
			catch (Exception)
			{
			}
			return "?";
		}

		private static Player ReadSender(PhotonMessageInfo info)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				return info.Sender;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not read the vote's sender\n" + ex));
				return null;
			}
		}

		private static string SafeNick(Player player)
		{
			try
			{
				if (player != null && !string.IsNullOrEmpty(player.NickName))
				{
					return player.NickName;
				}
			}
			catch (Exception)
			{
			}
			return "Player";
		}

		private static string Sanitize(string text)
		{
			if (string.IsNullOrEmpty(text))
			{
				return text;
			}
			return text.Replace('<', '(').Replace('>', ')');
		}
	}
}
namespace SVVote.Patches
{
	[HarmonyPatch(typeof(RunManager), "ChangeLevel")]
	internal static class ChangeLevelPatch
	{
		private static void Postfix()
		{
			if (!Plugin.IsHost || !Plugin.VotingActive)
			{
				return;
			}
			try
			{
				VoteService.SyncPhase(SemiFunc.RunIsLobby());
			}
			catch (Exception)
			{
			}
		}
	}
	[HarmonyPatch(typeof(PlayerAvatar), "ChatMessageSendRPC")]
	internal static class IncomingChatPatch
	{
		private static void Postfix(string _message, PhotonMessageInfo _info)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.IsHost)
			{
				return;
			}
			try
			{
				VoteService.HandleChat(_message, _info);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Incoming chat could not be parsed\n" + ex));
			}
		}
	}
	[HarmonyPatch(typeof(RunManager), "SetRunLevel")]
	internal static class SetRunLevelPatch
	{
		private static bool Prefix(RunManager __instance)
		{
			if (!Plugin.IsHost || !Plugin.VotingActive)
			{
				return true;
			}
			if (MapsBridge.Installed)
			{
				return true;
			}
			try
			{
				return VoteService.TryForcePendingLevel(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Vote level override failed; vanilla pick proceeds\n" + ex));
				return true;
			}
		}

		private static void Postfix(RunManager __instance)
		{
			if (!Plugin.IsHost || !Plugin.VotingActive || !MapsBridge.Installed)
			{
				return;
			}
			try
			{
				VoteService.ApplyMapsModeVote(__instance);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Vote mode stamp failed; Maps keeps its own round\n" + ex));
			}
		}
	}
}