Decompiled source of AutoItemBan v0.2.1

plugins/com.github.LengSword.AutoItemBan.dll

Decompiled a day ago
using System;
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;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using UnityEngine;
using Zorro.Core.Serizalization;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.LengSword.AutoItemBan")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.1.0")]
[assembly: AssemblyInformationalVersion("0.2.1+3ffb65c05251203881b928dd20c9f825231a4e42")]
[assembly: AssemblyProduct("com.github.LengSword.AutoItemBan")]
[assembly: AssemblyTitle("AutoItemBan")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.2.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 BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace AutoItemBan
{
	public static class ItemBanManager
	{
		private static HashSet<ushort>? configuredItemIDs;

		public static HashSet<ushort> GetConfiguredItemIDs(bool forceRefresh = false)
		{
			if (configuredItemIDs != null && !forceRefresh)
			{
				return configuredItemIDs;
			}
			string value = PluginConfig.ItemFilterPreset.Value;
			if (!PluginConfig.FilterPresets.TryGetValue(value, out string value2))
			{
				configuredItemIDs = new HashSet<ushort>();
				return configuredItemIDs;
			}
			if (value == "Custom")
			{
				value2 = PluginConfig.CustomItemFilterList.Value;
			}
			configuredItemIDs = ParseItemList(value2);
			return configuredItemIDs;
		}

		public static bool IsItemBanned(ushort itemID)
		{
			HashSet<ushort> hashSet = GetConfiguredItemIDs();
			if (!(PluginConfig.ItemFilterMode.Value == "Whitelist"))
			{
				return hashSet.Contains(itemID);
			}
			return !hashSet.Contains(itemID);
		}

		private static HashSet<ushort> ParseItemList(string itemList)
		{
			HashSet<ushort> hashSet = new HashSet<ushort>();
			string[] array = itemList.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries);
			string[] array2 = array;
			foreach (string text in array2)
			{
				string text2 = text.Trim();
				ushort result;
				if (PluginConfig.FilterPresets.TryGetValue(text2, out string value))
				{
					HashSet<ushort> other = ParseItemList(value);
					hashSet.UnionWith(other);
				}
				else if (ushort.TryParse(text2, out result))
				{
					hashSet.Add(result);
				}
			}
			return hashSet;
		}
	}
	[BepInPlugin("com.github.LengSword.AutoItemBan", "AutoItemBan", "0.2.1")]
	public class Plugin : BaseUnityPlugin
	{
		private static PlayerConnectionLog _playerConnectionLog;

		public const string Id = "com.github.LengSword.AutoItemBan";

		internal static ManualLogSource Logger { get; private set; }

		public static string Name => "AutoItemBan";

		public static string Version => "0.2.1";

		private void Awake()
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			Logger.LogInfo((object)("Plugin " + Name + " is loaded!"));
			PluginConfig.Initialize(((BaseUnityPlugin)this).Config, Logger);
			Harmony val = new Harmony("com.github.LengSword.AutoItemBan");
			val.PatchAll();
		}

		internal static bool NotifyPlayer(string message, bool onlyShowOnce = false, bool sound = false)
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_playerConnectionLog == (Object)null)
			{
				_playerConnectionLog = Object.FindAnyObjectByType<PlayerConnectionLog>();
			}
			if ((Object)(object)_playerConnectionLog == (Object)null)
			{
				Logger.LogWarning((object)"PlayerConnectionLog not found. Cannot show notification.");
				return false;
			}
			StringBuilder stringBuilder = new StringBuilder(message);
			stringBuilder.Replace("[[userColor]]", _playerConnectionLog.GetColorTag(_playerConnectionLog.userColor));
			stringBuilder.Replace("[[itemColor]]", _playerConnectionLog.GetColorTag(_playerConnectionLog.leftColor));
			message = stringBuilder.ToString();
			if (onlyShowOnce && _playerConnectionLog.currentLog.Contains(message))
			{
				return true;
			}
			if (_playerConnectionLog.currentLog.Count >= PluginConfig.AlertLinesLimit.Value)
			{
				_playerConnectionLog.currentLog.RemoveAt(0);
			}
			_playerConnectionLog.AddMessage(message);
			if (sound)
			{
				_playerConnectionLog.sfxLeave.Play(default(Vector3));
			}
			return true;
		}
	}
	public static class PluginConfig
	{
		internal static Dictionary<string, string> FilterPresets = new Dictionary<string, string>
		{
			{ "Custom", "" },
			{ "Abnormal", "113,193,175,74,72,28" }
		};

		internal static ConfigEntry<bool> EnableItemBan { get; private set; } = null;

		internal static ConfigEntry<string> ItemFilterMode { get; private set; } = null;

		internal static ConfigEntry<string> ItemFilterPreset { get; private set; } = null;

		internal static ConfigEntry<string> CustomItemFilterList { get; private set; } = null;

		internal static ConfigEntry<bool> ShowAlert { get; private set; } = null;

		internal static ConfigEntry<int> AlertLinesLimit { get; private set; } = null;

		public static void Initialize(ConfigFile config, ManualLogSource logger)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Expected O, but got Unknown
			EnableItemBan = config.Bind<bool>("General", "EnableItemBan", true, "Enable the item ban feature");
			ItemFilterMode = config.Bind<string>("General", "ItemFilterMode", "Blacklist", new ConfigDescription("How the configured list is interpreted. Blacklist: listed items are banned. Whitelist: items not listed are banned.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[2] { "Blacklist", "Whitelist" }), Array.Empty<object>()));
			ConfigDescription val = new ConfigDescription("Preset for item filter list. Options: Custom, Abnormal", (AcceptableValueBase)(object)new AcceptableValueList<string>(FilterPresets.Keys.ToArray()), Array.Empty<object>());
			ItemFilterPreset = config.Bind<string>("General", "ItemFilterPreset", "Abnormal", val);
			CustomItemFilterList = config.Bind<string>("General", "CustomItemFilterList", "", "A comma-separated list of item IDs or preset names. Example: Abnormal,1001,1002,1003");
			ShowAlert = config.Bind<bool>("General", "ShowAlert", true, "Show an alert message when a banned item is spawned or equipped by a player.");
			AlertLinesLimit = config.Bind<int>("General", "AlertLinesLimit", 4, new ConfigDescription("Maximum number of alert lines to keep in the notification log.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10), Array.Empty<object>()));
			ItemFilterMode.SettingChanged += delegate
			{
				logger.LogInfo((object)"Item filter mode changed, updating configured items...");
				ItemBanManager.GetConfiguredItemIDs(forceRefresh: true);
			};
			ItemFilterPreset.SettingChanged += delegate
			{
				logger.LogInfo((object)"Item filter preset changed, updating configured items...");
				ItemBanManager.GetConfiguredItemIDs(forceRefresh: true);
			};
			CustomItemFilterList.SettingChanged += delegate
			{
				logger.LogInfo((object)"Custom item filter list changed, updating configured items...");
				ItemBanManager.GetConfiguredItemIDs(forceRefresh: true);
			};
			logger.LogInfo((object)"Plugin Config Loaded.");
		}
	}
}
namespace AutoItemBan.Patches
{
	[HarmonyWrapSafe]
	internal sealed class NetworkInstantiatePatch
	{
		[HarmonyPatch(typeof(PhotonNetwork), "NetworkInstantiate", new Type[]
		{
			typeof(InstantiateParameters),
			typeof(bool),
			typeof(bool)
		})]
		[HarmonyPostfix]
		private static void PhotonNetworkNetworkInstantiatePatch(ref InstantiateParameters parameters, ref GameObject __result, bool instantiateEvent)
		{
			//IL_025b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0278: Unknown result type (might be due to invalid IL or missing references)
			if (!PluginConfig.EnableItemBan.Value || !PhotonNetwork.IsMasterClient || (Object)(object)__result == (Object)null)
			{
				return;
			}
			Plugin.Logger.LogDebug((object)$"{parameters.creator.NickName} (#{parameters.creator.ActorNumber}) instantiated the '{parameters.prefabName}' prefab.");
			string prefabName = parameters.prefabName;
			if (!prefabName.StartsWith("0_Items/"))
			{
				return;
			}
			string text = prefabName.Substring("0_Items/".Length);
			Item component = __result.GetComponent<Item>();
			if ((Object)(object)component == (Object)null)
			{
				return;
			}
			ushort itemID = component.itemID;
			if (!ItemBanManager.IsItemBanned(itemID))
			{
				return;
			}
			bool flag = PluginConfig.ItemFilterMode.Value == "Whitelist";
			string text2 = (flag ? "is not in whitelist" : "is banned");
			Plugin.Logger.LogDebug((object)$"Banned item '{text}' (ID: {itemID}) instantiated by {parameters.creator.NickName} (#{parameters.creator.ActorNumber}) {text2}. Removing item from the world.");
			if (PluginConfig.ShowAlert.Value)
			{
				string message = (flag ? $"[[userColor]] {parameters.creator.NickName}</color> tried to spawn a non-whitelisted item: [[itemColor]]{text} ({component.GetItemName((ItemInstanceData)null)})</color>[#{itemID}]" : $"[[userColor]] {parameters.creator.NickName}</color> tried to spawn a banned item: [[itemColor]]{text} ({component.GetItemName((ItemInstanceData)null)})</color>[#{itemID}]");
				Plugin.NotifyPlayer(message, onlyShowOnce: false, sound: true);
			}
			((Component)component).gameObject.SetActive(false);
			Player player = PlayerHandler.GetPlayer(parameters.creator);
			for (byte b = 0; b < player.itemSlots.Length; b++)
			{
				if (player.itemSlots[b] != null && !((Object)(object)player.itemSlots[b].prefab == (Object)null) && ItemBanManager.IsItemBanned(player.itemSlots[b].prefab.itemID))
				{
					player.itemSlots[b].EmptyOut();
					player.itemSlots[b].data = null;
				}
			}
			InventorySyncData val = default(InventorySyncData);
			((InventorySyncData)(ref val))..ctor(player.itemSlots, player.backpackSlot, player.tempFullSlot);
			player.view.RPC("SyncInventoryRPC", (RpcTarget)0, new object[2]
			{
				IBinarySerializable.ToManagedArray<InventorySyncData>(val),
				true
			});
			((MonoBehaviourPun)component).photonView.OwnershipTransfer = (OwnershipOption)2;
			((MonoBehaviourPun)component).photonView.OwnerActorNr = PhotonNetwork.LocalPlayer.ActorNumber;
			((MonoBehaviourPun)component).photonView.ControllerActorNr = PhotonNetwork.LocalPlayer.ActorNumber;
			((MonoBehaviourPun)component).photonView.RequestOwnership();
			((MonoBehaviourPun)component).photonView.TransferOwnership(PhotonNetwork.LocalPlayer);
			PhotonNetwork.Destroy(((MonoBehaviourPun)component).photonView);
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}