Decompiled source of ChatColors v1.0.7

BepInEx/plugins/StuntedRaccoon.ChatColors/StuntedRaccoon.CustomChatColors.dll

Decompiled 14 hours ago
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SQLite;
using System.Diagnostics;
using System.IO;
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.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mirror;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("StuntedRaccoon.CustomChatColors")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.2.0")]
[assembly: AssemblyInformationalVersion("1.0.2+24c896c053e89c0a1a5e3b0bc7408e97642cd4ea")]
[assembly: AssemblyProduct("CstmChatColor")]
[assembly: AssemblyTitle("StuntedRaccoon.CustomChatColors")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.2.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 CustomChatColors
{
	internal class ChatColorDatabase
	{
		private string _connectionStr;

		private string _tableName { get; } = "ChatColors";


		public ChatColorDatabase(string dbPath)
		{
			Console.WriteLine("Database path provided: " + dbPath);
			_connectionStr = "Data Source=" + dbPath;
			Init();
		}

		private void Init()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			SQLiteConnection val = new SQLiteConnection(_connectionStr);
			try
			{
				((DbConnection)(object)val).Open();
				string text = "\r\n                    CREATE TABLE IF NOT EXISTS " + _tableName + " (\r\n                        SteamID TEXT PRIMARY KEY,\r\n                        Color TEXT\r\n                    );\r\n                ";
				SQLiteCommand val2 = new SQLiteCommand(text, val);
				try
				{
					((DbCommand)(object)val2).ExecuteNonQuery();
				}
				finally
				{
					((IDisposable)val2)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public void RemoveUserColor(string steamID)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			SQLiteConnection val = new SQLiteConnection(_connectionStr);
			try
			{
				((DbConnection)(object)val).Open();
				string text = "\r\n                    DELETE FROM " + _tableName + " WHERE SteamID = @SteamID\r\n                ";
				SQLiteCommand val2 = new SQLiteCommand(text, val);
				try
				{
					val2.Parameters.AddWithValue("@SteamID", (object)steamID);
					((DbCommand)(object)val2).ExecuteNonQueryAsync();
				}
				finally
				{
					((IDisposable)val2)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		public string GetUserColor(string steamID)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			string result = null;
			SQLiteConnection val = new SQLiteConnection(_connectionStr);
			try
			{
				((DbConnection)(object)val).Open();
				string text = "\r\n                    SELECT * FROM " + _tableName + " WHERE SteamID = @SteamID;\r\n                ";
				SQLiteCommand val2 = new SQLiteCommand(text, val);
				try
				{
					val2.Parameters.AddWithValue("@SteamID", (object)steamID);
					SQLiteDataReader val3 = val2.ExecuteReader();
					try
					{
						if (((DbDataReader)(object)val3).Read())
						{
							result = ((DbDataReader)(object)val3)["Color"].ToString();
						}
					}
					finally
					{
						((IDisposable)val3)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val2)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			return result;
		}

		public Dictionary<string, string> GetAllColors()
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Expected O, but got Unknown
			Dictionary<string, string> dictionary = null;
			SQLiteConnection val = new SQLiteConnection(_connectionStr);
			try
			{
				((DbConnection)(object)val).Open();
				string text = "\r\n                    SELECT * FROM " + _tableName + ";\r\n                ";
				SQLiteCommand val2 = new SQLiteCommand(text, val);
				try
				{
					SQLiteDataReader val3 = val2.ExecuteReader();
					try
					{
						dictionary = new Dictionary<string, string>();
						while (((DbDataReader)(object)val3).Read())
						{
							string key = ((DbDataReader)(object)val3)["SteamID"].ToString();
							string value = ((DbDataReader)(object)val3)["Color"].ToString();
							dictionary[key] = value;
						}
					}
					finally
					{
						((IDisposable)val3)?.Dispose();
					}
				}
				finally
				{
					((IDisposable)val2)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
			return dictionary;
		}

		public void SetUserColor(string steamID, string color)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			SQLiteConnection val = new SQLiteConnection(_connectionStr);
			try
			{
				((DbConnection)(object)val).Open();
				string text = "\r\n                    INSERT INTO " + _tableName + " (SteamID, Color)\r\n                    VALUES (@SteamID, @Color)\r\n                    ON CONFLICT(SteamID) DO UPDATE SET Color = @Color;\r\n                ";
				SQLiteCommand val2 = new SQLiteCommand(text, val);
				try
				{
					val2.Parameters.AddWithValue("@SteamID", (object)steamID);
					val2.Parameters.AddWithValue("@Color", (object)color);
					((DbCommand)(object)val2).ExecuteNonQueryAsync();
				}
				finally
				{
					((IDisposable)val2)?.Dispose();
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}
	}
	[BepInPlugin("StuntedRaccoon.CustomChatColors", "CstmChatColor", "1.0.2")]
	public class Plugin : BaseUnityPlugin
	{
		[HarmonyPatch(typeof(ChatBehaviour), "Rpc_RecieveChatMessage")]
		public static class ChatBehaviour_Rpc_RecieveChatMessage
		{
			public static bool Prefix(ref ChatBehaviour __instance, ref string message)
			{
				bool flag = false;
				if (message != null)
				{
					Player component = ((Component)__instance).GetComponent<Player>();
					if ((Object)(object)component == (Object)null)
					{
						Logger.LogWarning((object)"ChatBehaviour instance had no Player component.");
						return true;
					}
					if (message.Contains("/chatcolor") && message.Length > 11 && message.Substring(0, 10).Equals("/chatcolor"))
					{
						string text = message.Substring(11);
						text = text.Replace(" ", "");
						string pattern = "^#([0-9A-Fa-f]{6})$";
						Regex regex = new Regex(pattern);
						bool flag2 = regex.IsMatch(text);
						if (text.ToLower().Equals("clear"))
						{
							_customChatColors.Remove(component._steamID);
							_noChatColors.Add(component._steamID);
							return false;
						}
						if (!flag2)
						{
							return true;
						}
						_customChatColors[component._steamID] = text;
						_noChatColors.Remove(component._steamID);
						flag = true;
					}
					if (_noChatColors.Contains(component._steamID))
					{
						return true;
					}
					if (!_customChatColors.TryGetValue(component._steamID, out var value))
					{
						string userColor = chatColorDatabase.GetUserColor(component._steamID);
						if (userColor == null)
						{
							_noChatColors.Add(component._steamID);
							return true;
						}
						_customChatColors.Add(component._steamID, userColor);
						value = userColor;
					}
					if (value != null)
					{
						message = "<color=" + value + ">" + message + "</color>";
					}
				}
				return !flag;
			}
		}

		[HarmonyPatch(typeof(AtlyssNetworkManager), "OnServerDisconnect")]
		public static class AtlyssNetworkManager_OnServerDisconnect
		{
			public static void Prefix(ref NetworkConnectionToClient _conn)
			{
				if (chatColorDatabase == null)
				{
					return;
				}
				List<HC_PeerListEntry> list = HostConsole._current?._peerListEntries;
				int connectionId = ((NetworkConnection)_conn).connectionId;
				Player val = null;
				if (list == null)
				{
					return;
				}
				for (int i = 0; i < list.Count; i++)
				{
					if (((ListDataEntry)list[i])._dataID == connectionId)
					{
						val = list[i]._peerPlayer;
						break;
					}
				}
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				string network_steamID = val.Network_steamID;
				if (network_steamID != null)
				{
					if (_customChatColors.TryGetValue(network_steamID, out var value))
					{
						chatColorDatabase.SetUserColor(network_steamID, value);
					}
					if (_noChatColors.Contains(network_steamID))
					{
						chatColorDatabase.RemoveUserColor(network_steamID);
					}
					_customChatColors.Remove(network_steamID);
					_noChatColors.Remove(network_steamID);
				}
			}
		}

		[HarmonyPatch(typeof(Player), "<Handle_ServerParameters>g__Handle_NicknameParams|79_0")]
		public static class Player_Handle_ServerConditions
		{
			public static bool Prefix()
			{
				return false;
			}
		}

		internal static ManualLogSource Logger;

		private static Dictionary<string, string> _customChatColors;

		private static HashSet<string> _noChatColors;

		private static ChatColorDatabase chatColorDatabase;

		private static string DatabaseFilename { get; } = "/chatColorDatabase";


		private void Awake()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Expected O, but got Unknown
			Logger = ((BaseUnityPlugin)this).Logger;
			Logger.LogInfo((object)"Plugin StuntedRaccoon.CustomChatColors is loaded!");
			_customChatColors = new Dictionary<string, string>();
			_noChatColors = new HashSet<string>();
			string assemblyDirectoryPath = GetAssemblyDirectoryPath();
			if (assemblyDirectoryPath != null)
			{
				chatColorDatabase = new ChatColorDatabase(assemblyDirectoryPath + DatabaseFilename);
			}
			else
			{
				Logger.LogError((object)"The database could not be created. Path was invalid");
			}
			Harmony val = new Harmony("StuntedRaccoon.CustomChatColors");
			val.PatchAll();
		}

		private string GetAssemblyDirectoryPath()
		{
			string result = null;
			try
			{
				string location = Assembly.GetExecutingAssembly().Location;
				string directoryName = Path.GetDirectoryName(location);
				result = directoryName;
			}
			catch (Exception)
			{
				Logger.LogWarning((object)"Failed to retrieve executing assembly directory.");
			}
			return result;
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "StuntedRaccoon.CustomChatColors";

		public const string PLUGIN_NAME = "CstmChatColor";

		public const string PLUGIN_VERSION = "1.0.2";
	}
}