Decompiled source of SteamGlobalName v1.0.1

SteamGlobalName.dll

Decompiled 3 weeks 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
using Nessie.ATLYSS.EasySettings;
using Steamworks;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.SteamGlobalName.sftwre")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+1ac667bbdd1fe326f4dfe1e65a331988a3092484")]
[assembly: AssemblyProduct("SteamGlobalName")]
[assembly: AssemblyTitle("SteamGlobalName")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SteamGlobalName
{
	[BepInPlugin("com.SteamGlobalName.sftwre", "SteamGlobalName", "1.0.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		private static readonly DateTime DeprecationDateUtc = new DateTime(2026, 10, 31, 0, 0, 0, DateTimeKind.Utc);

		internal static Plugin? Instance;

		internal static ManualLogSource Log;

		public static ConfigEntry<bool> UseSteamName;

		private readonly Dictionary<Player, string> originals = new Dictionary<Player, string>();

		private readonly HashSet<ulong> requested = new HashSet<ulong>();

		private ConfigEntry<string>? savedOriginalNickname;

		private ConfigEntry<bool>? hasSavedOriginalNickname;

		private Harmony? harmony;

		private bool isActive = true;

		private float labelTimer;

		private void Awake()
		{
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Expected O, but got Unknown
			//IL_0161: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: 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
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			if (DateTime.UtcNow >= DeprecationDateUtc)
			{
				DisableForDeprecation();
				return;
			}
			Log.LogWarning((object)(string.Format("{0} will disable itself on {1:yyyy-MM-dd} UTC. ", "SteamGlobalName", DeprecationDateUtc) + "Uninstall it and use RPNames instead: https://thunderstore.io/c/atlyss/p/s0apy/RPNames/"));
			UseSteamName = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Use Steam Name", true, "Set the global name from your Steam username. Off = use the local name.");
			savedOriginalNickname = ((BaseUnityPlugin)this).Config.Bind<string>("Internal", "Original Nickname", "", "Nickname saved before applying the Steam name.");
			hasSavedOriginalNickname = ((BaseUnityPlugin)this).Config.Bind<bool>("Internal", "Has Original Nickname", false, "Whether an original nickname is available to restore.");
			harmony = new Harmony("com.SteamGlobalName.sftwre");
			harmony.PatchAll(Assembly.GetExecutingAssembly());
			string[] array = (from method in harmony.GetPatchedMethods()
				select method.DeclaringType?.Name + "." + method.Name).ToArray();
			Log.LogInfo((object)("Installed Harmony patches: " + string.Join(", ", array)));
			if (array.Length == 0)
			{
				Log.LogError((object)"Harmony did not install any patches");
			}
			Settings.OnInitialized.AddListener(new UnityAction(AddSettings));
			Settings.OnApplySettings.AddListener((UnityAction)delegate
			{
				if (isActive)
				{
					Log.LogInfo((object)"Settings applied; refreshing labels and queuing nickname update");
					((BaseUnityPlugin)this).Config.Save();
					RefreshLabels();
					CharacterSelectManager characterSelect = Object.FindObjectOfType<CharacterSelectManager>();
					QueueApplySteamName(characterSelect);
				}
			});
			Log.LogInfo((object)"SteamGlobalName 1.0.1 loaded");
		}

		private void AddSettings()
		{
			if (isActive)
			{
				SettingsTab orAddCustomTab = Settings.GetOrAddCustomTab("SteamGlobalName");
				orAddCustomTab.AddHeader("Global Name");
				orAddCustomTab.AddToggle(UseSteamName);
			}
		}

		private void Update()
		{
			if (!isActive)
			{
				return;
			}
			if (DateTime.UtcNow >= DeprecationDateUtc)
			{
				DisableForDeprecation();
				return;
			}
			labelTimer += Time.deltaTime;
			if (labelTimer >= 1f)
			{
				labelTimer = 0f;
				RefreshLabels();
			}
		}

		internal void ApplySteamName(CharacterSelectManager characterSelect)
		{
			if (!isActive)
			{
				return;
			}
			if ((Object)(object)characterSelect == (Object)null)
			{
				Log.LogWarning((object)"Cannot apply Steam name: CharacterSelectManager was not found");
				return;
			}
			InputField globalNickanmeInput = characterSelect._globalNickanmeInput;
			if ((Object)(object)globalNickanmeInput == (Object)null)
			{
				Log.LogWarning((object)"Character select nickname input is not available");
				return;
			}
			if (savedOriginalNickname == null || hasSavedOriginalNickname == null)
			{
				Log.LogError((object)"Original nickname configuration is not initialized");
				return;
			}
			if (!UseSteamName.Value)
			{
				Log.LogInfo((object)"Steam global nickname setting is disabled");
				if (hasSavedOriginalNickname.Value)
				{
					string value = savedOriginalNickname.Value;
					Log.LogInfo((object)("Restoring nickname to '" + value + "' (input currently '" + globalNickanmeInput.text + "')"));
					SetInputText(globalNickanmeInput, value, activate: false);
					savedOriginalNickname.Value = "";
					hasSavedOriginalNickname.Value = false;
					((BaseUnityPlugin)this).Config.Save();
				}
				else
				{
					Log.LogInfo((object)"Steam name is disabled, but no original nickname is stored");
				}
				return;
			}
			string text = LocalSteamName();
			if (string.IsNullOrWhiteSpace(text))
			{
				Log.LogWarning((object)"Steam persona name is unavailable; cannot set the character select nickname");
				return;
			}
			if (!hasSavedOriginalNickname.Value && globalNickanmeInput.text != text)
			{
				savedOriginalNickname.Value = globalNickanmeInput.text;
				hasSavedOriginalNickname.Value = true;
				((BaseUnityPlugin)this).Config.Save();
				Log.LogInfo((object)("Saved original global nickname '" + globalNickanmeInput.text + "'"));
			}
			else if (!hasSavedOriginalNickname.Value)
			{
				Log.LogInfo((object)"Input already matches the Steam name; no original nickname was captured");
			}
			SetInputText(globalNickanmeInput, text, activate: true);
			Log.LogInfo((object)("Set character select global nickname to '" + text + "'"));
		}

		internal void QueueApplySteamName(CharacterSelectManager? characterSelect)
		{
			if (isActive)
			{
				((MonoBehaviour)this).StartCoroutine(ApplySteamNameAfterMenuUpdate(characterSelect));
			}
		}

		private IEnumerator ApplySteamNameAfterMenuUpdate(CharacterSelectManager? characterSelect)
		{
			yield return null;
			yield return (object)new WaitForSeconds(0.25f);
			if (!isActive)
			{
				yield break;
			}
			if ((Object)(object)characterSelect == (Object)null)
			{
				characterSelect = Object.FindObjectOfType<CharacterSelectManager>();
				if ((Object)(object)characterSelect == (Object)null)
				{
					Log.LogWarning((object)"CharacterSelectManager not found after waiting for the main menu to update");
					yield break;
				}
			}
			ApplySteamName(characterSelect);
		}

		private void DisableForDeprecation()
		{
			if (!isActive)
			{
				return;
			}
			isActive = false;
			Harmony? obj = harmony;
			if (obj != null)
			{
				obj.UnpatchSelf();
			}
			foreach (KeyValuePair<Player, string> original in originals)
			{
				if ((Object)(object)original.Key != (Object)null)
				{
					original.Key._globalNickname = original.Value;
				}
			}
			originals.Clear();
			if (savedOriginalNickname != null && hasSavedOriginalNickname != null && hasSavedOriginalNickname.Value)
			{
				CharacterSelectManager val = Object.FindObjectOfType<CharacterSelectManager>();
				InputField val2 = (((Object)(object)val == (Object)null) ? null : val._globalNickanmeInput);
				if ((Object)(object)val2 != (Object)null)
				{
					SetInputText(val2, savedOriginalNickname.Value, activate: false);
					savedOriginalNickname.Value = "";
					hasSavedOriginalNickname.Value = false;
					((BaseUnityPlugin)this).Config.Save();
				}
			}
			Log.LogWarning((object)(string.Format("{0} reached its deprecation date ({1:yyyy-MM-dd} UTC). ", "SteamGlobalName", DeprecationDateUtc) + "Harmony patches have been removed and this mod is now disabled. Uninstall it and use RPNames instead: https://thunderstore.io/c/atlyss/p/s0apy/RPNames/"));
			((Behaviour)this).enabled = false;
		}

		private static void SetInputText(InputField input, string text, bool activate)
		{
			if (!(input.text == text))
			{
				if (activate)
				{
					input.ActivateInputField();
				}
				input.text = text;
			}
		}

		internal void RefreshLabels()
		{
			Player[] array = Object.FindObjectsOfType<Player>();
			foreach (Player val in array)
			{
				if ((Object)(object)val != (Object)null)
				{
					UpdateLabel(val);
				}
			}
			foreach (Player item in originals.Keys.Where((Player k) => (Object)(object)k == (Object)null).ToList())
			{
				originals.Remove(item);
			}
		}

		private void UpdateLabel(Player p)
		{
			if (!UseSteamName.Value)
			{
				if (originals.TryGetValue(p, out string value))
				{
					p._globalNickname = value;
					originals.Remove(p);
				}
			}
			else
			{
				if (!ulong.TryParse(p._steamID, out var result))
				{
					return;
				}
				string text = (((NetworkBehaviour)p).isLocalPlayer ? LocalSteamName() : SteamNameFor(result));
				if (string.IsNullOrWhiteSpace(text))
				{
					return;
				}
				if (!originals.ContainsKey(p))
				{
					string globalNickname = p._globalNickname;
					if (string.IsNullOrEmpty(globalNickname))
					{
						return;
					}
					originals[p] = globalNickname;
				}
				if (p._globalNickname != text)
				{
					p._globalNickname = text;
				}
			}
		}

		private static string LocalSteamName()
		{
			if (!SteamManager.Initialized)
			{
				return null;
			}
			return SteamFriends.GetPersonaName();
		}

		private string SteamNameFor(ulong id)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			if (!SteamAPI.IsSteamRunning())
			{
				return null;
			}
			CSteamID val = default(CSteamID);
			((CSteamID)(ref val))..ctor(id);
			string friendPersonaName = SteamFriends.GetFriendPersonaName(val);
			if (string.IsNullOrWhiteSpace(friendPersonaName) || friendPersonaName == "[unknown]")
			{
				if (requested.Add(id))
				{
					SteamFriends.RequestUserInformation(val, true);
				}
				return null;
			}
			return friendPersonaName;
		}
	}
	[HarmonyPatch]
	public static class GameStatePatches
	{
		[HarmonyPatch(typeof(MainMenuManager), "Set_MenuCondition")]
		[HarmonyPostfix]
		public static void OnSetMenuCondition(MainMenuManager __instance)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)__instance._mainMenuCondition != 1)
			{
				return;
			}
			Plugin.Log.LogInfo((object)"Main menu entered character select");
			CharacterSelectManager characterSelectManager = __instance._characterSelectManager;
			if ((Object)(object)Plugin.Instance == (Object)null)
			{
				Plugin.Log.LogWarning((object)"Plugin.Instance is null; cannot apply Steam name");
				return;
			}
			if ((Object)(object)characterSelectManager == (Object)null)
			{
				Plugin.Log.LogWarning((object)"MainMenuManager._characterSelectManager is null; will search after a delay");
			}
			Plugin.Instance.QueueApplySteamName(characterSelectManager);
		}

		[HarmonyPatch(typeof(MainMenuManager), "Load_HostSettings")]
		[HarmonyPostfix]
		public static void OnLoadHostSettings(MainMenuManager __instance)
		{
			if ((Object)(object)Plugin.Instance == (Object)null)
			{
				Plugin.Log.LogWarning((object)"Plugin.Instance is null after host settings loaded");
				return;
			}
			CharacterSelectManager characterSelectManager = __instance._characterSelectManager;
			Plugin.Instance.QueueApplySteamName(characterSelectManager);
		}

		[HarmonyPatch(typeof(ProfileDataSender), "OnSend_CharacterFileData")]
		[HarmonyPostfix]
		public static void OnSendCharacterFileData()
		{
			CharacterSelectManager characterSelect = Object.FindObjectOfType<CharacterSelectManager>();
			if ((Object)(object)Plugin.Instance == (Object)null)
			{
				Plugin.Log.LogWarning((object)"Plugin.Instance is null after character file data was sent");
			}
			else
			{
				Plugin.Instance.QueueApplySteamName(characterSelect);
			}
		}
	}
	internal static class ModInfo
	{
		public const string GUID = "com.SteamGlobalName.sftwre";

		public const string NAME = "SteamGlobalName";

		public const string VERSION = "1.0.1";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}