Decompiled source of ChatService v2.7.0

ChatServicePlugin.dll

Decompiled 2 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using Bounce.Singletons;
using Bounce.Unmanaged;
using GameChat.UI;
using HarmonyLib;
using Newtonsoft.Json;
using TMPro;
using Talespire;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.SceneManagement;
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: AssemblyTitle("ChatServicePlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ChatServicePlugin")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("ChatServicePlugin")]
[assembly: ComVisible(false)]
[assembly: Guid("c303405d-e66c-4316-9cdb-4e3ca15c6360")]
[assembly: AssemblyFileVersion("2.7.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("2.7.0.0")]
namespace LordAshes;

[BepInPlugin("org.lordashes.plugins.chatservice", "Chat Service Plug-In", "2.7.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class ChatServicePlugin : BaseUnityPlugin
{
	[HarmonyPatch(typeof(UIChatMessageManager), "AddChatMessage")]
	public static class PatchAddChatMessage
	{
		public static bool Prefix(ref string creatureName, Texture2D icon, ref string chatMessage, IChatFocusable focus = null)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)"Chat Service Plugin: AddEventMessage Patch");
			}
			string text = creatureName;
			ApplyAliases(ref chatMessage);
			ProcessMessage(ref creatureName, ref chatMessage);
			if (chatMessage == null || (chatMessage.Trim() == "" && creatureName == text))
			{
				return false;
			}
			if (logFileNamePrefix.Value.Trim() != "")
			{
				LogChatMessage(creatureName, chatMessage);
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UIChatMessageManager), "AddEventMessage")]
	public static class PatchAddEventMessage
	{
		public static bool Prefix(ref string title, ref string message, IChatFocusable focus = null)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)"Chat Service Plugin: AddEventMessage Patch");
			}
			string text = title;
			ApplyAliases(ref message);
			ProcessMessage(ref title, ref message);
			if (message == null || (message.Trim() == "" && title == text))
			{
				return false;
			}
			if (logFileNamePrefix.Value.Trim() != "")
			{
				LogEventMessage(title, message);
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(UIChatMessageManager), "AddDiceResultMessage")]
	public static class PatchAddDiceResultMessage
	{
		public static bool Prefix(RollResults diceResult, ResultsOrigin origin, ClientGuid sender, bool hidden)
		{
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			if (logFileNamePrefix.Value.Trim() != "")
			{
				((MonoBehaviour)_self).StartCoroutine(LogDiceResult(diceResult, sender, hidden));
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(ChatInputBoardTool), "Begin")]
	public static class PatchBegin
	{
		public static void Postfix()
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)"Chat Service Plugin: Chat Entry Begin Prefix");
			}
			SetSpeaker();
		}
	}

	[HarmonyPatch(typeof(CreatureBoardAsset), "Speak")]
	public static class PatchSpeak
	{
		public static bool Prefix(string text)
		{
			return !CheckIfHandlersApply(text);
		}
	}

	public static class PatchAssistant
	{
		public static object GetProperty(object instance, string propertyName)
		{
			Type type = instance.GetType();
			foreach (PropertyInfo runtimeProperty in type.GetRuntimeProperties())
			{
				if (runtimeProperty.Name.Contains(propertyName))
				{
					return runtimeProperty.GetValue(instance);
				}
			}
			PropertyInfo[] properties = type.GetProperties();
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.Name.Contains(propertyName))
				{
					return propertyInfo.GetValue(instance);
				}
			}
			return null;
		}

		public static void SetProperty(object instance, string propertyName, object value)
		{
			Type type = instance.GetType();
			foreach (PropertyInfo runtimeProperty in type.GetRuntimeProperties())
			{
				if (runtimeProperty.Name.Contains(propertyName))
				{
					runtimeProperty.SetValue(instance, value);
					return;
				}
			}
			PropertyInfo[] properties = type.GetProperties();
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.Name.Contains(propertyName))
				{
					propertyInfo.SetValue(instance, value);
					break;
				}
			}
		}

		public static object GetField(object instance, string fieldName)
		{
			Type type = instance.GetType();
			foreach (FieldInfo runtimeField in type.GetRuntimeFields())
			{
				if (runtimeField.Name.Contains(fieldName))
				{
					return runtimeField.GetValue(instance);
				}
			}
			FieldInfo[] fields = type.GetFields();
			foreach (FieldInfo fieldInfo in fields)
			{
				if (fieldInfo.Name.Contains(fieldName))
				{
					return fieldInfo.GetValue(instance);
				}
			}
			return null;
		}

		public static void SetField(object instance, string fieldName, object value)
		{
			Type type = instance.GetType();
			foreach (FieldInfo runtimeField in type.GetRuntimeFields())
			{
				if (runtimeField.Name.Contains(fieldName))
				{
					runtimeField.SetValue(instance, value);
					return;
				}
			}
			FieldInfo[] fields = type.GetFields();
			foreach (FieldInfo fieldInfo in fields)
			{
				if (fieldInfo.Name.Contains(fieldName))
				{
					fieldInfo.SetValue(instance, value);
					break;
				}
			}
		}

		public static object UseMethod(object instance, string methodName, object[] parameters)
		{
			Type type = instance.GetType();
			foreach (MethodInfo runtimeMethod in type.GetRuntimeMethods())
			{
				if (runtimeMethod.Name.Contains(methodName))
				{
					return runtimeMethod.Invoke(instance, parameters);
				}
			}
			MethodInfo[] methods = type.GetMethods();
			foreach (MethodInfo methodInfo in methods)
			{
				if (methodInfo.Name.Contains(methodName))
				{
					return methodInfo.Invoke(instance, parameters);
				}
			}
			return null;
		}
	}

	public enum ChatSource
	{
		gm = 0,
		player = 1,
		creature = 2,
		hideVolume = 3,
		other = 888,
		anonymous = 999
	}

	public enum DiagnosticSelection
	{
		none = 0,
		low = 1,
		high = 2,
		ultra = 999,
		debug = 999
	}

	public static class ChatMessageService
	{
		public static void AddHandler(string key, Func<string, string, SourceRole, string> callback)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: Added Subscription To " + key));
			}
			chatMessgeServiceHandlers.Add(key, callback);
		}

		public static void RemoveHandler(string key)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: Removed Subscription To " + key));
			}
			chatMessgeServiceHandlers.Remove(key);
		}

		public static bool CheckHandler(string key)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: Check If Handler '" + key + "' Is Registered"));
			}
			return chatMessgeServiceHandlers.ContainsKey(key);
		}

		public static void SendMessage(string message, NGuid source)
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: Sending " + message + " (signature " + ((object)(NGuid)(ref source)).ToString() + ")"));
			}
			ChatManager.SendChatMessageToBoard(message, source, (float3?)null, false);
		}
	}

	public static class SDIM
	{
		public enum InvokeResult
		{
			success,
			missingFile,
			missingMethod,
			invalidParameters
		}

		public static object InvokeReturn;

		public static InvokeResult InvokeMethod(string pluginFile, string methodName, object[] parameters)
		{
			InvokeReturn = null;
			Type type = FindPlugin(pluginFile);
			if (type == null)
			{
				Debug.LogWarning((object)"Chat Service Plugin: SDIM: Missing File. Ignorning Soft Dependency Functionality.");
				return InvokeResult.missingFile;
			}
			MethodInfo method = type.GetMethod(methodName);
			if (method == null)
			{
				Debug.LogWarning((object)"Chat Service Plugin: SDIM: Missing Method. Ignorning Soft Dependency Functionality.");
				return InvokeResult.missingMethod;
			}
			try
			{
				InvokeReturn = method.Invoke(null, parameters);
				return InvokeResult.success;
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("Chat Service Plugin: SDIM: Failed Invoke: " + ex?.ToString() + ". Ignorning Soft Dependency Functionality."));
				return InvokeResult.invalidParameters;
			}
		}

		private static Type FindPlugin(string pluginFile)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: SDIM: Looking For " + Paths.PluginPath + "/" + pluginFile));
			}
			if (File.Exists(Paths.PluginPath + "/" + pluginFile))
			{
				Assembly assembly = Assembly.LoadFrom(Paths.PluginPath + "/" + pluginFile);
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)("Chat Service Plugin: SDIM: Assembly = " + Convert.ToString(assembly)));
				}
				if (assembly == null)
				{
					return null;
				}
				Type[] types = assembly.GetTypes();
				foreach (Type type in types)
				{
					if (diagnostics.Value >= DiagnosticSelection.ultra)
					{
						Debug.Log((object)("Chat Service Plugin: SDIM: Seeking 'BaseUnityPlugin' Type. Found '" + type.ToString() + "'. IsSubclassOf = " + type.IsSubclassOf(typeof(BaseUnityPlugin))));
					}
					if (type.IsSubclassOf(typeof(BaseUnityPlugin)))
					{
						return type;
					}
				}
			}
			else if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: SDIM: " + Paths.PluginPath + "/" + pluginFile + " Not Installed"));
			}
			return null;
		}
	}

	public static class Utility
	{
		public static bool isBoardLoaded()
		{
			return SimpleSingletonBehaviour<CameraController>.HasInstance && SingletonStateMBehaviour<BoardSessionManager, State<BoardSessionManager>>.HasInstance && !BoardSessionManager.IsLoading;
		}

		public static bool StrictKeyCheck(KeyboardShortcut check)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			if (!((KeyboardShortcut)(ref check)).IsUp())
			{
				return false;
			}
			KeyCode[] array = new KeyCode[6];
			RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
			KeyCode[] array2 = (KeyCode[])(object)array;
			foreach (KeyCode val in array2)
			{
				if (Input.GetKey(val) != ((KeyboardShortcut)(ref check)).Modifiers.Contains(val))
				{
					return false;
				}
			}
			return true;
		}

		public static Guid GuidFromString(string input)
		{
			using MD5 mD = MD5.Create();
			byte[] b = mD.ComputeHash(Encoding.Default.GetBytes(input));
			return new Guid(b);
		}

		public static GameObject GetBaseLoader(CreatureGuid cid)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CreatureBoardAsset val = null;
				CreaturePresenter.TryGetAsset(cid, ref val);
				if ((Object)(object)val != (Object)null)
				{
					Transform match = null;
					Traverse(((Component)val).transform, "BaseLoader", 0, 10, ref match);
					if ((Object)(object)match != (Object)null)
					{
						Debug.Log((object)("Log Chat Plugin: Base Loader '" + ((Object)match.GetChild(0)).name + "' Found"));
						return ((Component)match.GetChild(0)).gameObject;
					}
					Debug.LogWarning((object)"Log Chat Plugin: Could Not Find Base Loader");
					return null;
				}
				return null;
			}
			catch
			{
				return null;
			}
		}

		public static GameObject GetAssetLoader(CreatureGuid cid)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				CreatureBoardAsset val = null;
				CreaturePresenter.TryGetAsset(cid, ref val);
				if ((Object)(object)val != (Object)null)
				{
					Transform match = null;
					Traverse(((Component)val).transform, "AssetLoader", 0, 10, ref match);
					if ((Object)(object)match != (Object)null)
					{
						Debug.Log((object)("Log Chat Plugin: Asset Loader '" + ((Object)match.GetChild(0)).name + "' Found"));
						return ((Component)match.GetChild(0)).gameObject;
					}
					Debug.LogWarning((object)"Log Chat Plugin: Could Not Find Asset Loader");
					return null;
				}
				return null;
			}
			catch
			{
				return null;
			}
		}

		public static void Traverse(Transform root, string seek, int depth, int depthMax, ref Transform match)
		{
			try
			{
				if ((Object)(object)match != (Object)null)
				{
					return;
				}
				if (((Object)root).name == seek)
				{
					match = root;
					return;
				}
				foreach (Transform item in ExtensionMethods.Children(root))
				{
					if (depth < depthMax)
					{
						Traverse(item, seek, depth + 1, depthMax, ref match);
					}
				}
			}
			catch
			{
			}
		}

		public static float ParseFloat(string value)
		{
			return float.Parse(value, CultureInfo.InvariantCulture);
		}

		public static string GetCreatureName(string nameBlock)
		{
			if (nameBlock == null)
			{
				return "(Unknown)";
			}
			if (!nameBlock.Contains("<size=0>"))
			{
				return nameBlock;
			}
			return nameBlock.Substring(0, nameBlock.IndexOf("<size=0>")).Trim();
		}

		public static void PostOnMainPage(MemberInfo plugin)
		{
			SceneManager.sceneLoaded += delegate(Scene scene, LoadSceneMode mode)
			{
				//IL_0072: Unknown result type (might be due to invalid IL or missing references)
				//IL_0079: Expected O, but got Unknown
				try
				{
					if (((Scene)(ref scene)).name == "UI")
					{
						TextMeshProUGUI uITextByName = GetUITextByName("BETA");
						if (Object.op_Implicit((Object)(object)uITextByName))
						{
							((TMP_Text)uITextByName).text = "INJECTED BUILD - unstable mods";
						}
					}
					else
					{
						TextMeshProUGUI uITextByName2 = GetUITextByName("TextMeshPro Text");
						if (Object.op_Implicit((Object)(object)uITextByName2))
						{
							BepInPlugin val = (BepInPlugin)Attribute.GetCustomAttribute(plugin, typeof(BepInPlugin));
							if (((TMP_Text)uITextByName2).text.EndsWith("</size>"))
							{
								((TMP_Text)uITextByName2).text = ((TMP_Text)uITextByName2).text + "\n\nMods Currently Installed:\n";
							}
							TextMeshProUGUI val2 = uITextByName2;
							((TMP_Text)val2).text = ((TMP_Text)val2).text + "\nLord Ashes' " + val.Name + " - " + val.Version;
						}
					}
				}
				catch (Exception ex)
				{
					Debug.Log((object)ex);
				}
			};
		}

		private static TextMeshProUGUI GetUITextByName(string name)
		{
			TextMeshProUGUI[] array = Object.FindObjectsOfType<TextMeshProUGUI>();
			for (int i = 0; i < array.Length; i++)
			{
				if (((Object)array[i]).name == name)
				{
					return array[i];
				}
			}
			return null;
		}
	}

	public const string Name = "Chat Service Plug-In";

	public const string Guid = "org.lordashes.plugins.chatservice";

	public const string Version = "2.7.0.0";

	private static Dictionary<string, Func<string, string, SourceRole, string>> chatMessgeServiceHandlers = new Dictionary<string, Func<string, string, SourceRole, string>>();

	public static ConfigEntry<DiagnosticSelection> diagnostics;

	private static object padlock = new object();

	private static string logFileName = "";

	private static Dictionary<string, string> aliases = new Dictionary<string, string>();

	private static BaseUnityPlugin _self = null;

	private static ConfigEntry<string> timestampStyle { get; set; }

	private static ConfigEntry<string> headerStyle { get; set; }

	private static ConfigEntry<string> contentStyle { get; set; }

	private static ConfigEntry<string> logFileNamePrefix { get; set; }

	private static ConfigEntry<bool> logFileUseTimestamps { get; set; }

	private static ConfigEntry<string> ignoreChatServicesList { get; set; }

	private static ConfigEntry<float> diceResultDelay { get; set; }

	private static void ApplyAliases(ref string message)
	{
		foreach (KeyValuePair<string, string> alias in aliases)
		{
			if (diagnostics.Value >= DiagnosticSelection.ultra)
			{
				Debug.Log((object)("Chat Service Plugin: ApplyAliases: Replacing '" + alias.Key + "' with '" + alias.Value + "'"));
			}
			message = message.Replace("/" + alias.Key, "/" + alias.Value);
		}
		if (diagnostics.Value >= DiagnosticSelection.high)
		{
			Debug.Log((object)("Chat Service Plugin: ApplyAliases: Alias Message = '" + message + "'"));
		}
	}

	private static void ProcessMessage(ref string title, ref string message)
	{
		//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
		string name = title;
		if (diagnostics.Value >= DiagnosticSelection.ultra)
		{
			Debug.Log((object)("Chat Service Plugin: ParseMessage: Title = '" + Convert.ToString(title) + "' Message = '" + Convert.ToString(message) + "'"));
		}
		if (message.StartsWith("[") && message.Contains("]"))
		{
			title = message.Substring(1);
			title = title.Substring(0, title.IndexOf("]"));
			message = message.Substring(message.IndexOf("]") + 1).Trim();
			if (diagnostics.Value >= DiagnosticSelection.ultra)
			{
				Debug.Log((object)("Chat Service Plugin: ParseMessage: Header Adjustment: Title = '" + Convert.ToString(title) + "' Message = '" + Convert.ToString(message) + "'"));
			}
		}
		bool flag;
		do
		{
			flag = false;
			foreach (KeyValuePair<string, Func<string, string, SourceRole, string>> chatMessgeServiceHandler in chatMessgeServiceHandlers)
			{
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)("Chat Service Plugin: ParseMessage: Found Handler '" + chatMessgeServiceHandler.Key + "'"));
				}
				if (message.StartsWith(chatMessgeServiceHandler.Key))
				{
					if (diagnostics.Value >= DiagnosticSelection.high)
					{
						Debug.Log((object)("Chat Service Plugin: ParseMessage: Applying Handler '" + chatMessgeServiceHandler.Key + "'"));
					}
					try
					{
						message = chatMessgeServiceHandler.Value(message, title, FindSource(name));
					}
					catch (Exception ex)
					{
						Debug.LogWarning((object)("Chat Service Plugin: ParseMessage: Exception In Handler: " + ex.Message));
						Debug.LogException(ex);
						message = "";
					}
					if (diagnostics.Value >= DiagnosticSelection.ultra)
					{
						Debug.Log((object)("Chat Service Plugin: ParseMessage: Post Handler: Title = '" + Convert.ToString(title) + "' Message = '" + Convert.ToString(message) + "'"));
					}
					if (message == null || message.Trim() == "")
					{
						return;
					}
					flag = true;
					break;
				}
			}
		}
		while (flag);
	}

	private static bool CheckIfHandlersApply(string message)
	{
		foreach (KeyValuePair<string, Func<string, string, SourceRole, string>> chatMessgeServiceHandler in chatMessgeServiceHandlers)
		{
			if (diagnostics.Value >= DiagnosticSelection.ultra)
			{
				Debug.Log((object)("Chat Service Plugin: CheckIfHandlersApply: Handler: '" + chatMessgeServiceHandler.Key + "'"));
			}
			if (message.StartsWith(chatMessgeServiceHandler.Key))
			{
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)("Chat Service Plugin: CheckIfHandlersApply: Message Uses '" + chatMessgeServiceHandler.Key + "' Handler"));
				}
				return true;
			}
		}
		if (diagnostics.Value >= DiagnosticSelection.ultra)
		{
			Debug.Log((object)"Chat Service Plugin: CheckIfHandlersApply: Message Does Not Use Any Handler");
		}
		return false;
	}

	private static SourceRole FindSource(string name)
	{
		//IL_0022: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
		//IL_0056: Unknown result type (might be due to invalid IL or missing references)
		//IL_008d: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		if (name.ToUpper() == "ANONYMOUS")
		{
			return (SourceRole)999;
		}
		foreach (CreatureBoardAsset item in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets())
		{
			if (item.Name.StartsWith(name))
			{
				return (SourceRole)2;
			}
		}
		foreach (KeyValuePair<PlayerGuid, PlayerInfo> item2 in CampaignSessionManager.PlayersInfo)
		{
			if (CampaignSessionManager.GetPlayerName(item2.Key) == name)
			{
				if (item2.Value.Rights.CanGm)
				{
					return (SourceRole)0;
				}
				return (SourceRole)1;
			}
		}
		return (SourceRole)888;
	}

	private void Awake()
	{
		//IL_0209: Unknown result type (might be due to invalid IL or missing references)
		//IL_020f: Expected O, but got Unknown
		//IL_0263: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Unknown result type (might be due to invalid IL or missing references)
		//IL_0273: Unknown result type (might be due to invalid IL or missing references)
		//IL_0288: Unknown result type (might be due to invalid IL or missing references)
		//IL_028f: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b6: Expected O, but got Unknown
		_self = (BaseUnityPlugin)(object)this;
		diagnostics = ((BaseUnityPlugin)this).Config.Bind<DiagnosticSelection>("Settings", "Log Diagnostic Level", DiagnosticSelection.low, (ConfigDescription)null);
		Debug.Log((object)("Chat Service Plugin: " + ((object)this).GetType().AssemblyQualifiedName + " Active. (Diagnostics=" + diagnostics.Value.ToString() + ")"));
		timestampStyle = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "Timestamp Style", "font-size: 8pt; font-weight: normal; background-color: #454545;", (ConfigDescription)null);
		headerStyle = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "Header Style", "font-size: 16pt; font-weight: bold; background-color: #555555;", (ConfigDescription)null);
		contentStyle = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "Content Style", "font-size: 12pt; font-weight: normal; background-color: #656565;", (ConfigDescription)null);
		logFileNamePrefix = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "Chat Log File Name (Or Empty For Off)", "", (ConfigDescription)null);
		logFileUseTimestamps = ((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "Use Timestamp Log Filenames", true, (ConfigDescription)null);
		ignoreChatServicesList = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "List Of Chat Services To Not Log", "/org.lordashes.plugins.assetdata|", (ConfigDescription)null);
		diceResultDelay = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "Dice Result Message Processing Delay", 2f, (ConfigDescription)null);
		if (logFileNamePrefix.Value.Trim() != "")
		{
			logFileName = logFileNamePrefix.Value.Trim() + (logFileUseTimestamps.Value ? ("_" + DateTime.UtcNow.ToString("yyyy.MM.dd_HH.mm.ss")) : "") + ".html";
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)("Chat Service Plugin: Chat Log using " + logFileName));
			}
			File.WriteAllText(logFileName, "<HTML>\r\n  <BODY>\r\n");
		}
		Harmony val = new Harmony("org.lordashes.plugins.chatservice");
		val.PatchAll();
		if (!((BaseUnityPlugin)this).Config.Bind<bool>("Settings", "Add Deselect Option", true, (ConfigDescription)null).Value)
		{
			return;
		}
		if (diagnostics.Value >= DiagnosticSelection.ultra)
		{
			Debug.Log((object)"Chat Service Plugin: Creating Deselect Character Menu Option.");
		}
		ItemArgs val2 = new ItemArgs
		{
			Title = "Deselect",
			Icon = Image.LoadSprite("Deselect.png", (CacheType)999),
			CloseMenuOnActivate = true,
			Action = delegate
			{
				//IL_0027: Unknown result type (might be due to invalid IL or missing references)
				//IL_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)"Chat Service Plugin: Deselecting All Assets");
				}
				foreach (CreatureBoardAsset item in (IEnumerable<CreatureBoardAsset>)CreaturePresenter.GetTempReadOnlyViewOfAllCreatureAssets())
				{
					item.Deselect();
				}
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)"Chat Service Plugin: Updating LocalClient SelectedCreatureId");
				}
				PropertyInfo[] properties = typeof(LocalClient).GetProperties();
				foreach (PropertyInfo propertyInfo in properties)
				{
					if (propertyInfo.Name == "SelectedCreatureId")
					{
						if (diagnostics.Value >= DiagnosticSelection.ultra)
						{
							Debug.Log((object)"Chat Service Plugin: Found SelectedCreatureId. Updating...");
						}
						propertyInfo.SetValue(null, (object)default(CreatureGuid));
					}
					else if (diagnostics.Value >= DiagnosticSelection.ultra)
					{
						Debug.Log((object)("Chat Service Plugin: Found '" + propertyInfo.Name + "'"));
					}
				}
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)"Chat Service Plugin: Updating ChatInputBoardTool _selectedCreature");
				}
				ChatInputBoardTool instance = Object.FindObjectOfType<ChatInputBoardTool>();
				try
				{
					PatchAssistant.SetField(instance, "_selectedCreature", null);
				}
				catch
				{
				}
				SetSpeaker();
			}
		};
		if (SDIM.InvokeMethod("HolloFox_TS-RadialUIPlugin/RadialUI.dll", "AddCustomButtonOnCharacter", new object[3] { "org.lordashes.plugins.chatservice", val2, null }) == SDIM.InvokeResult.success)
		{
			if (diagnostics.Value >= DiagnosticSelection.high)
			{
				Debug.Log((object)"Chat Service Plugin: Adding Deselect Character Menu Option.");
			}
		}
		else if (diagnostics.Value >= DiagnosticSelection.high)
		{
			Debug.Log((object)"Chat Service Plugin: RadialUI Plugin Not Available");
		}
		if (!File.Exists("Chat_Service_Aliases.json"))
		{
			return;
		}
		aliases = JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText("Chat_Service_Aliases.json", (CacheType)999));
		if (diagnostics.Value < DiagnosticSelection.high)
		{
			return;
		}
		foreach (KeyValuePair<string, string> alias in aliases)
		{
			Debug.Log((object)("Chat Service Plugin: Adding Alias '/" + alias.Key + "' => '/" + alias.Value + "'"));
		}
	}

	public static void SetSpeaker()
	{
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Expected O, but got Unknown
		try
		{
			string text = "Someone";
			CreatureBoardAsset val = null;
			if (diagnostics.Value >= DiagnosticSelection.ultra)
			{
				Debug.Log((object)("Chat Service Plugin: Selected Characeter = " + Convert.ToString(LocalClient.SelectedCreatureId)));
			}
			CreaturePresenter.TryGetAsset(LocalClient.SelectedCreatureId, ref val);
			if ((Object)(object)val != (Object)null)
			{
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)"Chat Service Plugin: Setting Speaker Via Character Name");
				}
				text = val.Name;
				if (text.Contains("<"))
				{
					text = text.Substring(0, text.IndexOf("<"));
				}
			}
			else
			{
				if (diagnostics.Value >= DiagnosticSelection.ultra)
				{
					Debug.Log((object)"Chat Service Plugin: Setting Speaker Via Player Name");
				}
				text = CampaignSessionManager.GetPlayerName(LocalPlayer.Id);
			}
			ChatInputBoardTool val2 = Object.FindObjectOfType<ChatInputBoardTool>();
			if (!((Object)(object)val2 != (Object)null))
			{
				return;
			}
			UIChatInputField val3 = (UIChatInputField)PatchAssistant.GetField(val2, "_input");
			if ((Object)(object)val3 != (Object)null)
			{
				val3.UpdateSpeaker(text);
				if (diagnostics.Value >= DiagnosticSelection.high)
				{
					Debug.Log((object)("Chat Service Plugin: Speaker Set To " + text));
				}
			}
		}
		catch (Exception)
		{
		}
	}

	public static void LogChatMessage(string creatureName, string chatMessage, string directive = "")
	{
		if (chatMessage.Trim() != "")
		{
			string text = "    <DIV Width=480 Style=\"Width: 480px; border-style: solid;\">\r\n";
			text = text + "      <DIV Width=480 Id=Header Style=\"Width: 480px;" + timestampStyle.Value + "\">&nbsp;&nbsp;&nbsp;" + DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + "</DIV>\r\n";
			text = text + "      <DIV Width=480 Id=Header Style=\"Width: 480px;" + headerStyle.Value + "\">&nbsp;&nbsp;&nbsp;" + Utility.GetCreatureName(creatureName) + "</DIV>\r\n";
			if (directive != "")
			{
				text = text + "      <DIV Width=480 Id=Header Style=\"Width: 480px;" + timestampStyle.Value + "\">&nbsp;&nbsp;&nbsp;Operation: " + directive + "</DIV>\r\n";
			}
			text = text + "      <DIV Width=480 Id=Content Style=\"Width: 480px;" + contentStyle.Value + "\">&nbsp;&nbsp;&nbsp;" + chatMessage + "</DIV>\r\n";
			text += "    </DIV><BR>\r\n";
			lock (padlock)
			{
				File.AppendAllText(logFileName, text);
			}
		}
	}

	public static void LogEventMessage(string title, string message, string directive = "")
	{
		if (message.Trim() != "")
		{
			string text = "    <DIV Width=480 Style=\"Width: 480px; border-style: solid;\">\r\n";
			text = text + "      <DIV Width=480 Id=Header Style=\"Width: 480px;" + timestampStyle.Value + "\">&nbsp;&nbsp;&nbsp;" + DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + "</DIV>\r\n";
			text = text + "      <DIV Width=480 Id=Header Style=\"Width: 480px;" + headerStyle.Value + "\">&nbsp;&nbsp;&nbsp;" + Utility.GetCreatureName(title) + "</DIV>\r\n";
			if (directive != "")
			{
				text = text + "      <DIV Width=480 Id=Header Style=\"Width: 480px;" + timestampStyle.Value + "\">&nbsp;&nbsp;&nbsp;Operation: " + directive + "</DIV>\r\n";
			}
			text = text + "      <DIV Width=480 Id=Content Style=\"Width: 480px;" + contentStyle.Value + "\">&nbsp;&nbsp;&nbsp;" + message + "</DIV>\r\n";
			text += "    </DIV><BR>\r\n";
			lock (padlock)
			{
				File.AppendAllText(logFileName, text);
			}
		}
	}

	public static IEnumerator LogDiceResult(RollResults diceResult, ClientGuid sender, bool hidden)
	{
		//IL_000e: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		yield return (object)new WaitForSeconds(diceResultDelay.Value);
		string rollString = "";
		GameObject[] results = (from go in Object.FindObjectsOfType<GameObject>()
			where ((Object)go).name == "UI_DiceRollGroup(Clone)"
			select go).ToArray();
		if (results.Length == 0)
		{
			results = (from go in Object.FindObjectsOfType<GameObject>()
				where ((Object)go).name == "SingleDice"
				select go).ToArray();
			if (diagnostics.Value >= DiagnosticSelection.ultra)
			{
				Debug.Log((object)("Chat Service Plug-In: Found " + results.Length + " Single-Die Entries"));
			}
			GameObject target = results[^1];
			foreach (Transform asset in ExtensionMethods.Children(target.transform))
			{
				Debug.Log((object)("Chat Service Plug-In: Found Child " + ((Object)asset).name));
			}
			GameObject header = ((Component)(from go in ExtensionMethods.Children(target.transform)
				where ((Object)go).name == "TXT_Rolled"
				select go).ToArray()[0]).gameObject;
			string header_txt = ((TMP_Text)header.gameObject.GetComponentInChildren<TextMeshProUGUI>()).text;
			if (header_txt.StartsWith("Rolled "))
			{
				header_txt = header_txt.Substring("Rolled ".Length);
			}
			if (header_txt.StartsWith("And "))
			{
				header_txt = header_txt.Substring("And ".Length);
			}
			GameObject die = ((Component)(from go in ExtensionMethods.Children(target.transform)
				where ((Object)go).name == "UI_SingleDiceResult"
				select go).ToArray()[0]).gameObject;
			TextMeshProUGUI tmp3 = die.gameObject.GetComponentInChildren<TextMeshProUGUI>();
			RawImage img2 = die.gameObject.GetComponentInChildren<RawImage>();
			string text = rollString;
			string text2 = rollString + "\r\n" + header_txt + ": " + ((Object)((Graphic)img2).mainTexture).name.Substring(1) + "(" + ((TMP_Text)tmp3).text + ")";
			rollString = text + text2;
		}
		else
		{
			if (diagnostics.Value >= DiagnosticSelection.ultra)
			{
				Debug.Log((object)("Chat Service Plug-In: Found " + results.Length + " Multi-Part Entries"));
			}
			GameObject[] array = results;
			foreach (GameObject target2 in array)
			{
				GameObject result2 = target2;
				if ((Object)(object)result2 != (Object)null)
				{
					GameObject header2 = ((Component)(from go in ExtensionMethods.Children(result2.transform)
						where ((Object)go).name == "TXT_Header"
						select go).ToArray()[0]).gameObject;
					if ((Object)(object)header2 != (Object)null)
					{
						string header_txt2 = ((TMP_Text)header2.gameObject.GetComponentInChildren<TextMeshProUGUI>()).text;
						if (header_txt2.StartsWith("Rolled "))
						{
							header_txt2 = header_txt2.Substring("Rolled ".Length);
						}
						if (header_txt2.StartsWith("And "))
						{
							header_txt2 = header_txt2.Substring("And ".Length);
						}
						if (diagnostics.Value >= DiagnosticSelection.high)
						{
							Debug.Log((object)("Chat Service Plug-In: Processing " + header_txt2));
						}
						rollString = rollString + "\r\n" + header_txt2 + ": ";
						result2 = ((Component)(from go in ExtensionMethods.Children(result2.transform)
							where ((Object)go).name == "Root"
							select go).ToArray()[0]).gameObject;
						if ((Object)(object)result2 != (Object)null)
						{
							string lastOp = "";
							foreach (Transform t in ExtensionMethods.Children(result2.transform))
							{
								switch (((Object)t).name)
								{
								case "UI_SingleDiceResult(Clone)":
								{
									TextMeshProUGUI tmp3 = ((Component)t).gameObject.GetComponentInChildren<TextMeshProUGUI>();
									if (!lastOp.StartsWith("UI_SingleDiceResult"))
									{
										RawImage img = ((Component)t).gameObject.GetComponentInChildren<RawImage>();
										rollString += ((Object)((Graphic)img).mainTexture).name.Substring(1);
									}
									rollString = (lastOp.StartsWith("UI_SingleDiceResult") ? (rollString + "," + ((TMP_Text)tmp3).text) : (rollString + "(" + ((TMP_Text)tmp3).text));
									lastOp = ((Object)t).name;
									break;
								}
								case "UI_Operator(Clone)":
								{
									TextMeshProUGUI tmp3 = ((Component)t).gameObject.GetComponentInChildren<TextMeshProUGUI>();
									if (((TMP_Text)tmp3).text.Trim() != "(" && ((TMP_Text)tmp3).text.Trim() != ")")
									{
										rollString = (lastOp.StartsWith("UI_SingleDiceResult") ? (rollString + ")" + ((TMP_Text)tmp3).text) : (rollString + ((TMP_Text)tmp3).text));
										lastOp = ((Object)t).name;
									}
									break;
								}
								case "UI_DiceTotalText(Clone)":
								{
									TextMeshProUGUI tmp3 = ((Component)t).gameObject.GetComponentInChildren<TextMeshProUGUI>();
									rollString = (lastOp.StartsWith("UI_SingleDiceResult") ? (rollString + ")" + ((TMP_Text)tmp3).text) : (rollString + ((TMP_Text)tmp3).text));
									lastOp = ((Object)t).name;
									break;
								}
								}
							}
						}
						else
						{
							Debug.LogWarning((object)"Chat Service Plug-In: Failed To Find 'Root'");
						}
					}
					else
					{
						Debug.LogWarning((object)"Chat Service Plug-In: Failed To Find 'TXT_Header'");
					}
				}
				else
				{
					Debug.LogWarning((object)"Chat Service Plug-In: Failed To Find 'UI_DiceRollGroup(Clone)'");
				}
			}
		}
		if (diagnostics.Value >= DiagnosticSelection.high)
		{
			Debug.Log((object)("Chat Service Plug-In: Roll = " + rollString));
		}
		PlayerGuid roller = default(PlayerGuid);
		int rollerIndex = default(int);
		BoardSessionManager.ClientsPlayerGuids.TryGetValueIndex(sender, ref roller, ref rollerIndex);
		LogChatMessage(Utility.GetCreatureName(CampaignSessionManager.GetPlayerName(roller)), ToHTML(rollString));
	}

	public static string ToHTML(string text)
	{
		if (text.StartsWith("\r\n"))
		{
			text = text.Substring(2);
		}
		if (text.EndsWith("\r\n"))
		{
			text = text.Substring(0, text.Length - 2);
		}
		text = "<B>" + text;
		text = text.Replace(":", ":</B>");
		text = text.Replace("=", "=<B>");
		text = text.Replace("\r\n", "</B><BR><B>");
		return text;
	}
}
public static class StringExtensionMethods
{
	public static string ReplaceFirst(this string text, string search, string replace)
	{
		int num = text.IndexOf(search);
		if (num < 0)
		{
			return text;
		}
		return text.Substring(0, num) + replace + text.Substring(num + search.Length);
	}
}

plugins/SourceRole.dll

Decompiled 2 months ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("SourceRole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SourceRole")]
[assembly: AssemblyCopyright("Copyright ©  2022")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("08b45a92-bf19-40cb-9712-436e153d8fcf")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace Talespire;

public enum SourceRole
{
	gm = 0,
	player = 1,
	creature = 2,
	hideVolume = 3,
	other = 888,
	anonymous = 999
}