Decompiled source of SymbioteApiPlugin v1.2.0

SymbioteApiPlugin.dll

Decompiled a year 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 System.Web;
using BepInEx;
using BepInEx.Configuration;
using Bounce.Singletons;
using Newtonsoft.Json;
using Symbiotes;
using TMPro;
using Talespire;
using UnityEngine;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("SymbioteApiPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SymbioteApiPlugin")]
[assembly: AssemblyCopyright("Copyright ©  2023")]
[assembly: AssemblyTrademark("SymbioteApiPlugin")]
[assembly: ComVisible(false)]
[assembly: Guid("c303405d-e66c-4316-9cdb-4e3ca15c6360")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.2.0.0")]
namespace LordAshes;

[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("org.lordashes.plugins.symbioteapi", "Symbiote API Plugin", "1.2.0.0")]
public sealed class SymbioteApiPlugin : BaseUnityPlugin
{
	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)("Symbiote API Plugin: Base Loader '" + ((Object)match.GetChild(0)).name + "' Found"));
						return ((Component)match.GetChild(0)).gameObject;
					}
					Debug.LogWarning((object)"Symbiote API 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)("Symbiote API Plugin: Asset Loader '" + ((Object)match.GetChild(0)).name + "' Found"));
						return ((Component)match.GetChild(0)).gameObject;
					}
					Debug.LogWarning((object)"Symbiote API 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 enum DiagnosticLevel
	{
		none,
		error,
		warning,
		info,
		debug,
		ultra
	}

	public class Subscription
	{
		public Guid id { get; set; }

		public List<string> events { get; set; }

		public Action<string> callback { get; set; }
	}

	public class EventMessage
	{
		public string kind { get; set; }

		public object payload { get; set; }
	}

	public const string Name = "Symbiote API Plugin";

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

	public const string Version = "1.2.0.0";

	public const string Author = "Lord Ashes";

	private static string symbiotePrefix = "";

	private static List<Subscription> subscriptions = new List<Subscription>();

	private static string jsApiPrefix = "API:";

	private static List<Action> _callbacks = new List<Action>();

	private static ConfigEntry<DiagnosticLevel> diagnostics { get; set; }

	private void Awake()
	{
		diagnostics = ((BaseUnityPlugin)this).Config.Bind<DiagnosticLevel>("Settings", "Diagnostic Level", DiagnosticLevel.info, (ConfigDescription)null);
		Debug.Log((object)("Symbiote API Plugin: Active. (Diagnostic Mode = " + diagnostics.Value.ToString() + ")"));
		ChatMessageService.AddHandler("API:", (Func<string, string, SourceRole, string>)SymbioteIDCallback);
		ChatMessageService.AddHandler("PLUGIN:", (Func<string, string, SourceRole, string>)SymbiotePluginCallback);
		ChatMessageService.AddHandler("EVENT:", (Func<string, string, SourceRole, string>)SymbioteEventCallback);
		CreateSymbiote();
		((MonoBehaviour)this).StartCoroutine(ResponseFailure(((BaseUnityPlugin)this).Config.Bind<float>("Setting", "Symbiote Response Delay", 30f, (ConfigDescription)null).Value));
		Utility.PostOnMainPage(((object)this).GetType());
	}

	private void CreateSymbiote()
	{
		if (diagnostics.Value >= DiagnosticLevel.debug)
		{
			Debug.Log((object)"Symbiote API Plugin: Creating Symbiote API Symbiote");
		}
		string text = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Symbiote\\";
		string text2 = SymbiotesManager.GetSymbiotesDirectoryPath() + "\\";
		if (diagnostics.Value >= DiagnosticLevel.debug)
		{
			Debug.Log((object)("Symbiote API Plugin: Source = " + text));
		}
		if (diagnostics.Value >= DiagnosticLevel.debug)
		{
			Debug.Log((object)("Symbiote API Plugin: Destination = " + text2));
		}
		try
		{
			Directory.CreateDirectory(text2 + "\\LordAshes-Symbiote_Api");
		}
		catch (Exception ex)
		{
			Debug.Log((object)("Symbiote API Plugin: Exception: " + ex));
		}
		foreach (string item in Directory.EnumerateFiles(text))
		{
			if (diagnostics.Value >= DiagnosticLevel.ultra)
			{
				Debug.Log((object)("Symbiote API Plugin: Copying '" + item + "' To '" + text2 + "\\LordAshes-Symbiote_Api\\" + Path.GetFileName(item) + "'"));
			}
			try
			{
				File.Copy(item, text2 + "\\LordAshes-Symbiote_Api\\" + Path.GetFileName(item), overwrite: true);
			}
			catch (Exception ex2)
			{
				Debug.Log((object)("Symbiote API Plugin: Exception: " + ex2));
			}
		}
	}

	private string SymbioteIDCallback(string message, string sender, SourceRole arg3)
	{
		if (diagnostics.Value >= DiagnosticLevel.info)
		{
			Debug.Log((object)("Symbiote API Plugin: Symbiote ID = " + message + " (" + sender + ")"));
		}
		symbiotePrefix = message.Substring(4);
		foreach (Action callback in _callbacks)
		{
			callback?.Invoke();
		}
		return null;
	}

	private IEnumerator ResponseFailure(float delay)
	{
		yield return (object)new WaitForSeconds(delay);
		while (symbiotePrefix == "")
		{
			if (Utility.isBoardLoaded())
			{
				if (diagnostics.Value >= DiagnosticLevel.debug)
				{
					Debug.LogWarning((object)"Symbiote API Plugin: Symbiote API Not Active.");
				}
				SystemMessage.DisplayInfoText("Required Symbiote:\r\nPlease Re-Activate 'Symbiote API' Symbiote\r\nIn The Symbiote Panel", 10f);
			}
			yield return (object)new WaitForSeconds(delay);
		}
		if (diagnostics.Value >= DiagnosticLevel.debug)
		{
			Debug.Log((object)"Symbiote API Plugin: Symbiote API Active.");
		}
	}

	private string SymbiotePluginCallback(string message, string sender, SourceRole arg3)
	{
		//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
		message = message.Substring("PLUGIN:".Length);
		if (diagnostics.Value >= DiagnosticLevel.info)
		{
			Debug.Log((object)("Symbiote API Plugin: Symbiote Plugin = " + message));
		}
		string[] array = message.Split(new char[1] { ':' });
		CreatureGuid selectedCreatureId;
		switch (array[0].ToUpper())
		{
		case "SEND":
			AssetDataPlugin.SendInfo(array[1], array[2]);
			break;
		case "SET":
			if (array[1] == "*")
			{
				selectedCreatureId = LocalClient.SelectedCreatureId;
				array[1] = ((object)(CreatureGuid)(ref selectedCreatureId)).ToString();
			}
			AssetDataPlugin.SetInfo(array[1], array[2], array[3], bool.Parse(array[4]));
			break;
		case "CLEAR":
			if (array[1] == "*")
			{
				selectedCreatureId = LocalClient.SelectedCreatureId;
				array[1] = ((object)(CreatureGuid)(ref selectedCreatureId)).ToString();
			}
			AssetDataPlugin.ClearInfo(array[1], array[2], bool.Parse(array[3]));
			break;
		}
		return null;
	}

	private string SymbioteEventCallback(string message, string sender, SourceRole arg3)
	{
		message = message.Substring("EVENT:".Length);
		if (diagnostics.Value >= DiagnosticLevel.info)
		{
			Debug.Log((object)("Symbiote API Plugin: Symbiote Event = " + message));
		}
		EventMessage eventMessage = JsonConvert.DeserializeObject<EventMessage>(message);
		foreach (Subscription subscription in subscriptions)
		{
			if (subscription.events.Contains(eventMessage.kind))
			{
				subscription.callback(message);
			}
		}
		return null;
	}

	public static void Symbiote_API(string js)
	{
		if (diagnostics.Value >= DiagnosticLevel.debug)
		{
			Debug.Log((object)("Symbiote API Plugin: Triggering: " + Paths.GameRootPath + "\\TalespireUrlRelay.exe " + symbiotePrefix + jsApiPrefix + HttpUtility.UrlEncode(js)));
		}
		js = js.Replace(" ", "\u00a0");
		Process process = new Process
		{
			StartInfo = new ProcessStartInfo
			{
				FileName = Paths.GameRootPath + "\\TalespireUrlRelay.exe",
				Arguments = symbiotePrefix + jsApiPrefix + HttpUtility.UrlEncode(js),
				CreateNoWindow = true,
				RedirectStandardOutput = true,
				RedirectStandardError = true,
				UseShellExecute = false
			}
		};
		process.Start();
		string text = process.StandardError.ReadToEnd();
		process.WaitForExit();
		if (text != null && text.Trim() != "")
		{
			Debug.LogException(new Exception("Symbiote API Plugin: Execution Error: " + text));
		}
	}

	public static void Initialized(Action callback)
	{
		Debug.Log((object)"Symbiote API Plugin: Initialization Complete Callback Set");
		if (symbiotePrefix == "")
		{
			_callbacks.Add(callback);
		}
		else
		{
			callback();
		}
	}

	public static Guid Subscribe(List<string> events, Action<string> callback)
	{
		Subscription subscription = new Subscription
		{
			id = System.Guid.NewGuid(),
			events = events,
			callback = callback
		};
		subscriptions.Add(subscription);
		foreach (Subscription subscription2 in subscriptions)
		{
			Debug.Log((object)("Symbiote API Plugin: Subscription: " + subscription2.id.ToString() + ": " + string.Join(",", subscription2.events)));
		}
		RebuildSubscription();
		return subscription.id;
	}

	public static int Unsubscribe(Guid id)
	{
		int num = 0;
		for (int i = 0; i < subscriptions.Count; i++)
		{
			if (subscriptions[i].id == id)
			{
				subscriptions.RemoveAt(i);
				num++;
			}
		}
		RebuildSubscription();
		return num;
	}

	private static void RebuildSubscription()
	{
		List<string> list = new List<string>();
		foreach (Subscription subscription in subscriptions)
		{
			foreach (string @event in subscription.events)
			{
				if (!list.Contains(@event))
				{
					list.Add(@event);
				}
			}
		}
		if (diagnostics.Value >= DiagnosticLevel.debug)
		{
			Debug.Log((object)("Symbiote API Plugin: Symbiote Subscription: " + string.Join(",", list)));
		}
		Symbiote_API("Subscribe('" + string.Join(",", list) + "')");
	}
}