Decompiled source of ServerChatCommands v1.0.5

plugins\ServerChatCommands\ServerChatCommands.dll

Decompiled 4 days 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 BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using UnityEngine;

[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("ServerChatCommands")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ServerChatCommands")]
[assembly: AssemblyTitle("ServerChatCommands")]
[assembly: AssemblyVersion("1.0.5.0")]
namespace ServerChatCommands;

[BepInPlugin("org.bepinex.plugins.serverchatcommands", "ServerChatCommands", "1.0.5")]
public class Plugin : BaseUnityPlugin
{
	public const string ModGUID = "org.bepinex.plugins.serverchatcommands";

	public const string ModName = "ServerChatCommands";

	public const string ModVersion = "1.0.5";

	internal static Plugin Instance;

	internal static ManualLogSource Log;

	private Harmony _harmony;

	public static ConfigEntry<bool> ModEnabled;

	public static ConfigEntry<int> BannerDisplayType;

	public static ConfigEntry<int> DefaultDiceSides;

	public static ConfigEntry<int> MaxDiceSides;

	public static ConfigEntry<float> IrlTimeOffsetHours;

	public static ConfigEntry<string> IrlTimeLabel;

	internal static int ChatMessageHash;

	internal static int SayHash;

	public static ConfigEntry<bool> UseSystemLocalTime;

	private void Awake()
	{
		//IL_0122: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Expected O, but got Unknown
		Instance = this;
		Log = ((BaseUnityPlugin)this).Logger;
		ModEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Enable or disable ServerChatCommands.");
		BannerDisplayType = ((BaseUnityPlugin)this).Config.Bind<int>("Display", "BannerType", 2, "Notification banner style: 1 = TopLeft notification, 2 = Center banner.");
		DefaultDiceSides = ((BaseUnityPlugin)this).Config.Bind<int>("Commands", "DefaultDiceSides", 20, "Default die size for !roll (e.g. 20 for d20).");
		MaxDiceSides = ((BaseUnityPlugin)this).Config.Bind<int>("Commands", "MaxDiceSides", 1000000, "Maximum allowed die size for !roll.");
		UseSystemLocalTime = ((BaseUnityPlugin)this).Config.Bind<bool>("Time", "UseSystemLocalTime", true, "Use the local computer's system time and time zone instead of manual UTC offset.");
		IrlTimeOffsetHours = ((BaseUnityPlugin)this).Config.Bind<float>("Time", "IrlTimeOffsetHours", -7f, "Hours offset from UTC for IRL clock (e.g. -7 for PDT, -8 for PST, -5 for EST, 0 for UTC).");
		IrlTimeLabel = ((BaseUnityPlugin)this).Config.Bind<string>("Time", "IrlTimeLabel", "PT", "Label for IRL time zone (e.g. PST, PDT, PT, EST, UTC).");
		ChatMessageHash = StringExtensionMethods.GetStableHashCode("ChatMessage");
		SayHash = StringExtensionMethods.GetStableHashCode("Say");
		_harmony = new Harmony("org.bepinex.plugins.serverchatcommands");
		_harmony.PatchAll();
		Log.LogInfo((object)string.Format("{0} v{1} loaded successfully! Registered RPC hashes: ChatMessage={2}, Say={3}", "ServerChatCommands", "1.0.5", ChatMessageHash, SayHash));
	}

	private void OnDestroy()
	{
		Harmony harmony = _harmony;
		if (harmony != null)
		{
			harmony.UnpatchSelf();
		}
	}

	public static void Broadcast(string message)
	{
		try
		{
			int num = BannerDisplayType.Value;
			if (num != 1 && num != 2)
			{
				num = 2;
			}
			if (ZRoutedRpc.instance != null)
			{
				ZRoutedRpc.instance.InvokeRoutedRPC(0L, "ShowMessage", new object[2] { num, message });
			}
			else if ((Object)(object)MessageHud.instance != (Object)null)
			{
				MessageHud.instance.ShowMessage((MessageType)num, message, 0, (Sprite)null, false, true);
			}
			Log.LogInfo((object)("[ChatCommand Broadcast] " + message));
		}
		catch (Exception arg)
		{
			Log.LogError((object)$"Failed to broadcast message: {arg}");
		}
	}
}
[HarmonyPatch(typeof(ZRoutedRpc), "RouteRPC")]
public static class RouteRPCPatch
{
	[HarmonyPrefix]
	public static void Prefix(RoutedRPCData rpcData)
	{
		if (rpcData != null)
		{
			ChatInterceptor.ProcessRoutedRPC(rpcData);
		}
	}
}
[HarmonyPatch(typeof(ZRoutedRpc), "HandleRoutedRPC")]
public static class HandleRoutedRPCPatch
{
	[HarmonyPostfix]
	public static void Postfix(RoutedRPCData data)
	{
		if (data != null)
		{
			ChatInterceptor.ProcessRoutedRPC(data);
		}
	}
}
public static class ChatInterceptor
{
	private static readonly Dictionary<string, float> RecentMessages = new Dictionary<string, float>();

	private const float DuplicateWindowSeconds = 2f;

	private const int MaxTracked = 256;

	private static readonly string[] OracleAnswers = new string[15]
	{
		"The Allfather nods in favor.", "Thor strikes with a resounding yes!", "The runes foretell glorious victory.", "Freya smiles warmly upon this path.", "By the glory of Valhalla, yes.", "The ravens bring glad tidings; proceed!", "The mists of Niflheim conceal the outcome.", "The Norns weave an uncertain fate.", "The wind shifts; consult the ravens once more.", "The tides of destiny are murmuring, wait and see.",
		"Odin frowns upon this path.", "Loki weaves deceit; trust it not.", "Hel closes her gates; the answer is no.", "Dark omens gather; turn back while you can.", "A troll's misfortune awaits that choice."
	};

	public static void ProcessRoutedRPC(RoutedRPCData data)
	{
		//IL_0080: Unknown result type (might be due to invalid IL or missing references)
		//IL_0087: Expected O, but got Unknown
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a9: Expected O, but got Unknown
		//IL_00df: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e6: Expected O, but got Unknown
		if (!Plugin.ModEnabled.Value || data == null || data.m_parameters == null || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer())
		{
			return;
		}
		bool flag = data.m_methodHash == Plugin.ChatMessageHash;
		bool flag2 = data.m_methodHash == Plugin.SayHash;
		if ((!flag && !flag2) || IsDuplicate(data))
		{
			return;
		}
		string text = null;
		string text2 = null;
		try
		{
			byte[] array = data.m_parameters.GetArray();
			if (array == null || array.Length == 0)
			{
				return;
			}
			ZPackage val = new ZPackage(array);
			val.SetPos(0);
			if (flag)
			{
				val.ReadVector3();
				val.ReadInt();
				UserInfo val2 = new UserInfo();
				val2.Deserialize(ref val);
				text2 = val2.GetDisplayName();
				if (string.IsNullOrEmpty(text2))
				{
					text2 = val2.Name;
				}
				text = val.ReadString();
			}
			else if (flag2)
			{
				val.ReadInt();
				UserInfo val3 = new UserInfo();
				val3.Deserialize(ref val);
				text2 = val3.GetDisplayName();
				if (string.IsNullOrEmpty(text2))
				{
					text2 = val3.Name;
				}
				text = val.ReadString();
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Failed to deserialize chat packet: " + ex.Message));
			return;
		}
		if (string.IsNullOrEmpty(text))
		{
			return;
		}
		text = text.Trim();
		if (text.StartsWith("!"))
		{
			if (string.IsNullOrEmpty(text2))
			{
				ZNet instance = ZNet.instance;
				ZNetPeer val4 = ((instance != null) ? instance.GetPeer(data.m_senderPeerID) : null);
				text2 = ((val4 == null || string.IsNullOrEmpty(val4.m_playerName)) ? "Viking" : val4.m_playerName);
			}
			ExecuteCommand(text2, text);
		}
	}

	private static bool IsDuplicate(RoutedRPCData data)
	{
		try
		{
			byte[] array = data.m_parameters.GetArray();
			if (array == null || array.Length == 0)
			{
				return false;
			}
			uint num = 2166136261u;
			for (int i = 0; i < array.Length; i++)
			{
				num = (num ^ array[i]) * 16777619;
			}
			string key = $"{data.m_senderPeerID}:{data.m_methodHash}:{num}";
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (RecentMessages.TryGetValue(key, out var value) && realtimeSinceStartup - value < 2f)
			{
				return true;
			}
			RecentMessages[key] = realtimeSinceStartup;
			if (RecentMessages.Count > 256)
			{
				List<string> list = new List<string>();
				foreach (KeyValuePair<string, float> recentMessage in RecentMessages)
				{
					if (realtimeSinceStartup - recentMessage.Value > 10f)
					{
						list.Add(recentMessage.Key);
					}
				}
				foreach (string item in list)
				{
					RecentMessages.Remove(item);
				}
			}
		}
		catch (Exception ex)
		{
			Plugin.Log.LogWarning((object)("Duplicate check error: " + ex.Message));
		}
		return false;
	}

	private static void ExecuteCommand(string player, string rawText)
	{
		string[] array = rawText.Split(new char[1] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
		if (array.Length == 0)
		{
			return;
		}
		string text = array[0].ToLowerInvariant();
		if (text == null)
		{
			return;
		}
		switch (text.Length)
		{
		default:
			return;
		case 5:
		{
			char c = text[1];
			if ((uint)c <= 104u)
			{
				if (c != 'c')
				{
					if (c != 'h' || !(text == "!help"))
					{
						return;
					}
					break;
				}
				if (!(text == "!coin"))
				{
					return;
				}
				goto IL_0189;
			}
			switch (c)
			{
			case 'r':
				if (text == "!roll")
				{
					HandleRoll(player, array);
				}
				break;
			case 't':
				if (text == "!time")
				{
					HandleTime();
				}
				break;
			}
			return;
		}
		case 9:
		{
			char c = text[3];
			if (c != 'a')
			{
				if (c != 'i')
				{
					if (c != 'm' || !(text == "!commands"))
					{
						return;
					}
					break;
				}
				if (!(text == "!coinflip"))
				{
					return;
				}
				goto IL_0189;
			}
			if (!(text == "!playtime"))
			{
				return;
			}
			goto IL_019e;
		}
		case 7:
			switch (text[2])
			{
			default:
				return;
			case 'r':
				break;
			case 'p':
				goto IL_0149;
			case 'n':
				goto IL_0157;
			case 'o':
			case 'q':
				return;
			}
			if (!(text == "!oracle"))
			{
				return;
			}
			goto IL_0190;
		case 6:
			if (!(text == "!8ball"))
			{
				return;
			}
			goto IL_0190;
		case 4:
			if (text == "!afk")
			{
				HandleAfk(player, array);
			}
			return;
		case 8:
			{
				if (!(text == "!players"))
				{
					return;
				}
				goto IL_01ac;
			}
			IL_019e:
			HandlePlaytime();
			return;
			IL_0157:
			if (!(text == "!online"))
			{
				return;
			}
			goto IL_01ac;
			IL_01ac:
			HandleOnline();
			return;
			IL_0149:
			if (!(text == "!uptime"))
			{
				return;
			}
			goto IL_019e;
			IL_0189:
			HandleCoinflip(player);
			return;
			IL_0190:
			Handle8Ball(player, array);
			return;
		}
		HandleHelp();
	}

	private static void HandleRoll(string player, string[] parts)
	{
		int num = Plugin.DefaultDiceSides.Value;
		if (parts.Length > 1 && int.TryParse(parts[1], out var result) && result >= 2)
		{
			num = Math.Min(result, Plugin.MaxDiceSides.Value);
		}
		int num2 = Random.Range(1, num + 1);
		Plugin.Broadcast($"<color=#FFA500>\ud83c\udfb2 {player} rolled a d{num} and got a </color><color=#FF3333><b>{num2}</b></color><color=#FFA500>!</color>");
	}

	private static void HandleCoinflip(string player)
	{
		string text = ((Random.value < 0.5f) ? "Heads" : "Tails");
		Plugin.Broadcast("<color=#FFA500>\ud83e\ude99 " + player + " flipped a coin: " + text + "!</color>");
	}

	private static void Handle8Ball(string player, string[] parts)
	{
		string question = ((parts.Length > 1) ? string.Join(" ", parts, 1, parts.Length - 1) : null);
		int num = Random.Range(0, OracleAnswers.Length);
		string text = OracleAnswers[num];
		if ((Object)(object)Plugin.Instance != (Object)null)
		{
			((MonoBehaviour)Plugin.Instance).StartCoroutine(OracleRoutine(player, question, text));
			return;
		}
		Plugin.Broadcast("<color=#66CCFF>\ud83d\udd2e Oracle speaks to " + player + ": \"" + text + "\"</color>");
	}

	private static IEnumerator OracleRoutine(string player, string question, string answer)
	{
		Plugin.Broadcast((!string.IsNullOrEmpty(question)) ? ("<color=#66CCFF>\ud83d\udd2e " + player + " asks the Oracle: \"" + question + "\"</color>") : ("<color=#66CCFF>\ud83d\udd2e " + player + " consults the Oracle...</color>"));
		yield return (object)new WaitForSeconds(3f);
		Plugin.Broadcast("<color=#66CCFF>\ud83d\udd2e The Oracle speaks: \"" + answer + "\"</color>");
	}

	private static void HandleTime()
	{
		int num = ((!((Object)(object)EnvMan.instance != (Object)null)) ? 1 : EnvMan.instance.GetDay());
		float num2 = (((Object)(object)EnvMan.instance != (Object)null) ? EnvMan.instance.GetDayFraction() : 0f) * 24f;
		int num3 = (int)num2;
		int num4 = (int)((num2 - (float)num3) * 60f);
		string text = ((num3 >= 5 && num3 < 9) ? "Morning" : ((num3 >= 9 && num3 < 17) ? "Day" : ((num3 < 17 || num3 >= 21) ? "Night" : "Evening")));
		string text3;
		if (Plugin.UseSystemLocalTime.Value)
		{
			DateTime now = DateTime.Now;
			string text2 = now.ToString("h:mm tt");
			TimeZoneInfo local = TimeZoneInfo.Local;
			text3 = text2 + " " + (local.IsDaylightSavingTime(now) ? local.DaylightName : local.StandardName);
		}
		else
		{
			text3 = DateTime.UtcNow.AddHours(Plugin.IrlTimeOffsetHours.Value).ToString("h:mm tt") + " " + Plugin.IrlTimeLabel.Value;
		}
		Plugin.Broadcast($"<color=#A0E0FF>⏳ In-Game: Day {num}, {text} ({num3:D2}:{num4:D2}) | IRL: {text3}</color>");
	}

	private static void HandlePlaytime()
	{
		int num = ((!((Object)(object)EnvMan.instance != (Object)null)) ? 1 : EnvMan.instance.GetDay());
		TimeSpan timeSpan = TimeSpan.FromSeconds(((Object)(object)ZNet.instance != (Object)null) ? ZNet.instance.GetTimeSeconds() : 0.0);
		int num2 = (int)timeSpan.TotalHours;
		int minutes = timeSpan.Minutes;
		Plugin.Broadcast($"<color=#A0E0FF>\ud83d\udcdc Server Age: Day {num} | Active Playtime: {num2}h {minutes}m</color>");
	}

	private static void HandleAfk(string player, string[] parts)
	{
		string text = ((parts.Length > 1) ? string.Join(" ", parts, 1, parts.Length - 1) : null);
		Plugin.Broadcast((!string.IsNullOrEmpty(text)) ? ("<color=#FFB347>\ud83d\udca4 " + player + " is now AFK (" + text + ")</color>") : ("<color=#FFB347>\ud83d\udca4 " + player + " is now AFK</color>"));
	}

	private static void HandleOnline()
	{
		ZNet instance = ZNet.instance;
		List<ZNetPeer> list = ((instance != null) ? instance.GetPeers() : null);
		int num = list?.Count ?? 0;
		List<string> list2 = new List<string>();
		if (list != null)
		{
			float num3 = default(float);
			float num4 = default(float);
			float num5 = default(float);
			float num6 = default(float);
			foreach (ZNetPeer item in list)
			{
				string arg = ((!string.IsNullOrEmpty(item.m_playerName)) ? item.m_playerName : "Viking");
				int num2 = 0;
				if (item.m_socket != null)
				{
					item.m_socket.GetConnectionQuality(ref num3, ref num4, ref num2, ref num5, ref num6);
				}
				list2.Add($"{arg} ({num2}ms)");
			}
		}
		string arg2 = ((list2.Count > 0) ? string.Join(", ", list2) : "None");
		Plugin.Broadcast($"<color=#77DD77>\ud83d\udee1\ufe0f Online Vikings ({num}): {arg2}</color>");
	}

	private static void HandleHelp()
	{
		Plugin.Broadcast("<color=#FFA500>Commands: !roll [sides], !coinflip, !8ball [question], !time, !playtime, !afk [note], !online, !pin</color>");
	}
}