Decompiled source of PlaySoundPlugin v1.1.0

PlaySoundPlugin.dll

Decompiled a month 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 TMPro;
using UnityEngine;
using UnityEngine.Networking;
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("PlaySoundPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PlaySoundPlugin")]
[assembly: AssemblyCopyright("Copyright ©  2024")]
[assembly: AssemblyTrademark("PlaySoundPlugin")]
[assembly: ComVisible(false)]
[assembly: Guid("c303405d-e66c-4316-9cdb-4e3ca15c6360")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.1.0.0")]
namespace LordAshes;

[BepInPlugin("org.lordashes.plugins.playsound", "Play Sound Plugin", "1.1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public class PlaySoundPlugin : BaseUnityPlugin
{
	public static class Utility
	{
		public static bool isBoardLoaded()
		{
			return SimpleSingletonBehaviour<CameraController>.HasInstance && SingletonStateMBehaviour<BoardSessionManager, State<BoardSessionManager>>.HasInstance && !BoardSessionManager.IsLoading;
		}

		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 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 const string Name = "Play Sound Plugin";

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

	public const string Version = "1.1.0.0";

	public const string Author = "Lord Ashes";

	private KeyboardShortcut[] triggers = (KeyboardShortcut[])(object)new KeyboardShortcut[12]
	{
		new KeyboardShortcut((KeyCode)256, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)257, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)258, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)259, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)260, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)261, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)262, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)263, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)264, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)265, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)271, Array.Empty<KeyCode>()),
		new KeyboardShortcut((KeyCode)270, Array.Empty<KeyCode>())
	};

	private static string audioFilePattern = "";

	private static int digits = 0;

	private static float statusDisplayDuration = 3f;

	private static string buffer = "";

	private static int guiX = 10;

	private static int guiY = 30;

	private static string statusMessage = "";

	private static string root = "";

	private static GuiMenu menu = null;

	private static Texture2D[] icons = (Texture2D[])(object)new Texture2D[5];

	private static PlaySoundPlugin _self = null;

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

	private void Awake()
	{
		_self = this;
		diagnostics = ((BaseUnityPlugin)this).Config.Bind<DiagnosticLevel>("Settings", "Diagnostic Level", DiagnosticLevel.info, (ConfigDescription)null);
		Debug.Log((object)("Play Sound Plugin: Active. (Diagnostic Mode = " + diagnostics.Value.ToString() + ")"));
		audioFilePattern = ((BaseUnityPlugin)this).Config.Bind<string>("Settings", "Audio file location and file name", "http://MusicRepo.Org/Audio/#.mp3", (ConfigDescription)null).Value;
		root = Path.GetDirectoryName(audioFilePattern);
		if (!root.Replace("\\", "/").EndsWith("/"))
		{
			root += "/";
		}
		digits = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "Number of code digits", 3, (ConfigDescription)null).Value;
		guiX = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "UI X position", 10, (ConfigDescription)null).Value;
		guiY = ((BaseUnityPlugin)this).Config.Bind<int>("Settings", "UI Y position", 30, (ConfigDescription)null).Value;
		statusDisplayDuration = ((BaseUnityPlugin)this).Config.Bind<float>("Settings", "Status display duration in seconds", 3f, (ConfigDescription)null).Value;
		buffer = new string(' ', digits);
		icons[0] = Image.LoadTexture("org.lordashes.plugins.playsound/folderIcon.png", (CacheType)999);
		icons[1] = Image.LoadTexture("org.lordashes.plugins.playsound/backIcon.png", (CacheType)999);
		icons[2] = Image.LoadTexture("org.lordashes.plugins.playsound/soundIcon.png", (CacheType)999);
		icons[3] = Image.LoadTexture("org.lordashes.plugins.playsound/ambientIcon.png", (CacheType)999);
		icons[4] = Image.LoadTexture("org.lordashes.plugins.playsound/musicIcon.png", (CacheType)999);
		AssetDataPlugin.Subscribe("org.lordashes.plugins.playsound", (Action<DatumChange>)RequestHandler);
		Utility.PostOnMainPage(((object)this).GetType());
	}

	private void Update()
	{
		if (!Utility.isBoardLoaded())
		{
			return;
		}
		for (int i = 0; i < 10; i++)
		{
			if (((KeyboardShortcut)(ref triggers[i])).IsUp())
			{
				buffer = buffer.Substring(1) + i;
				if ("0123456789".Contains(buffer.Substring(0, 1)))
				{
					Debug.Log((object)("Play Sound Plugin: Requesting Audio Code '" + buffer + "'"));
					AssetDataPlugin.SendInfo("org.lordashes.plugins.playsound", buffer);
				}
			}
		}
		if (((KeyboardShortcut)(ref triggers[10])).IsUp())
		{
			buffer = new string(' ', digits);
		}
		if (!((KeyboardShortcut)(ref triggers[11])).IsUp())
		{
			return;
		}
		Debug.Log((object)"Play Sound Plugin: Generating Menu");
		GenerateMenu();
		menu.Open("Root", (Action<string>)delegate(string s)
		{
			Debug.Log((object)("Play Sound Plugin: Audio File '" + s + "' Requested"));
			if (Path.GetExtension(s).ToUpper() == ".WWW")
			{
				s = File.ReadAllText(root + s);
			}
			AssetDataPlugin.SendInfo("org.lordashes.plugins.playsound", s);
			menu.Close();
		});
	}

	private void OnGUI()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0084: Unknown result type (might be due to invalid IL or missing references)
		if (!buffer.EndsWith(" "))
		{
			GUI.Label(new Rect((float)guiX, (float)guiY, 320f, 30f), "Sound Code (" + digits + "): " + buffer);
		}
		else if (statusMessage != "")
		{
			GUI.Label(new Rect((float)guiX, (float)guiY, 320f, 30f), statusMessage);
		}
		if (menu != null)
		{
			menu.Draw();
		}
	}

	private void RequestHandler(DatumChange change)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Invalid comparison between Unknown and I4
		statusMessage = "Loading Audio...";
		if ((int)change.action != 1)
		{
			((MonoBehaviour)_self).StartCoroutine(PlayAudio(change.value.ToString()));
		}
		else
		{
			((MonoBehaviour)_self).StartCoroutine(PlayAudio(""));
		}
	}

	private IEnumerator PlayAudio(string audio)
	{
		Debug.Log((object)"Audio Plugin: Getting Audio Speaker");
		GameObject speaker = GameObject.Find("AudioSpeaker");
		if ((Object)(object)speaker == (Object)null)
		{
			Debug.Log((object)"Audio Plugin: Creating Audio Speaker");
			speaker = new GameObject();
			((Object)speaker).name = "AudioSpeaker";
			speaker.AddComponent<AudioSource>();
		}
		Debug.Log((object)"Audio Plugin: Creating Audio Speaker Source");
		AudioSource player = speaker.GetComponent<AudioSource>();
		if (!audio.ToUpper().StartsWith("HTTPS:") && !audio.ToUpper().StartsWith("HTTPS:"))
		{
			audio = audioFilePattern.Replace("#", audio);
		}
		if (!audio.Contains("/" + new string('0', digits) + ".") && audio != "")
		{
			UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(audio, (AudioType)0);
			try
			{
				yield return www.SendWebRequest();
				if ((int)www.result == 2)
				{
					Debug.Log((object)("Audio Plugin: Failure To Load " + audio + "..."));
					Debug.Log((object)www.error);
				}
				else
				{
					statusMessage = "Playing Audio...";
					buffer = new string(' ', digits);
					Debug.Log((object)"Audio Plugin: Downloading File");
					player.clip = DownloadHandlerAudioClip.GetContent(www);
					Debug.Log((object)"Audio Plugin: Playing");
					player.Play();
				}
			}
			finally
			{
				((IDisposable)www)?.Dispose();
			}
		}
		else
		{
			statusMessage = "Stopping Audio...";
			player.Stop();
			buffer = new string(' ', digits);
		}
		yield return (object)new WaitForSeconds(statusDisplayDuration);
		statusMessage = "";
	}

	private GuiMenu GenerateMenu()
	{
		//IL_0005: Unknown result type (might be due to invalid IL or missing references)
		//IL_000f: Expected O, but got Unknown
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0025: Expected O, but got Unknown
		//IL_0108: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Expected O, but got Unknown
		//IL_0367: Unknown result type (might be due to invalid IL or missing references)
		//IL_0375: Unknown result type (might be due to invalid IL or missing references)
		//IL_037f: Expected O, but got Unknown
		//IL_02a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_02bf: Expected O, but got Unknown
		menu = new GuiMenu(32, 36);
		Dictionary<string, MenuNode> dictionary = new Dictionary<string, MenuNode>();
		dictionary.Add("Root", new MenuNode());
		List<string> audioFiles = GetAudioFiles();
		foreach (string item in audioFiles)
		{
			string text = "Root";
			string[] array = Path.GetDirectoryName(item).Replace("\\", "/").Split(new char[1] { '/' });
			foreach (string text2 in array)
			{
				Debug.Log((object)("Play Sound Plugin: Entry '" + item + "' Looking At Part '" + text2 + "'"));
				if (!dictionary.ContainsKey(text + "/" + text2))
				{
					Debug.Log((object)("Play Sound Plugin: Creating Node '" + text + "/" + text2 + "'"));
					MenuNode val = new MenuNode();
					Debug.Log((object)("Play Sound Plugin: Creating Link From Node '" + text + "/" + text2 + "' Back To '" + text + "'"));
					val.AddLink(text, "", icons[1]);
					Debug.Log((object)("Play Sound Plugin: Adding Node '" + text + "'"));
					dictionary.Add(text + "/" + text2, val);
				}
				bool flag = false;
				Debug.Log((object)("Play Sound Plugin: Searching For Link Between '" + text + "' And '" + text + "/" + text2 + "'"));
				IMenuItem[] items = dictionary[text].GetItems();
				foreach (IMenuItem val2 in items)
				{
					Debug.Log((object)("Play Sound Plugin: Found Entry '" + val2.title + "'"));
					if (val2.title == text2)
					{
						Debug.Log((object)"Play Sound Plugin: Link Already Exists.");
						flag = true;
						break;
					}
				}
				if (!flag)
				{
					Debug.Log((object)("Play Sound Plugin: Link Does Not Exist. Creating Link From '" + text + "' To '" + text + "/" + text2 + "'"));
					dictionary[text].AddLink(new MenuLink(text + "/" + text2, text2, Color.red, icons[0], false));
				}
				text = text + "/" + text2;
			}
			int num = 2;
			if (item.ToUpper().Contains("AMBIENT"))
			{
				num = 3;
			}
			if (item.ToUpper().Contains("MUSIC"))
			{
				num = 4;
			}
			Debug.Log((object)("Play Sound Plugin: Adding Selection '" + Path.GetFileNameWithoutExtension(item) + "' Using Icon Index " + num + " To Node"));
			dictionary[text].AddSelection(new MenuSelection(item, Path.GetFileNameWithoutExtension(item), Color.red, icons[num], false));
		}
		foreach (KeyValuePair<string, MenuNode> item2 in dictionary)
		{
			Debug.Log((object)("Play Sound Plugin: Adding Node '" + item2.Key + "' To The Menu"));
			item2.Value.name = item2.Key;
			item2.Value.style = (MenuStyle)1;
			menu.AddNode(item2.Value);
		}
		return menu;
	}

	private List<string> GetAudioFiles()
	{
		List<string> entries = new List<string>();
		Traverse(root, root, ref entries);
		return entries;
	}

	private void Traverse(string path, string root, ref List<string> entries)
	{
		Debug.Log((object)("Play Sound Plugin: Enumerating '" + path + "'"));
		path = path.Replace("\\", "/");
		foreach (string item in from f in Directory.EnumerateFiles(path)
			where ".ACC|.MP3|.OGG|.WAV|.WWW".Contains(Path.GetExtension(f).ToUpper())
			select f)
		{
			entries.Add(item.Substring(root.Length).Replace("\\", "/"));
		}
		foreach (string item2 in Directory.EnumerateDirectories(path))
		{
			Traverse(item2, root, ref entries);
		}
	}
}