Decompiled source of allonlytrumpetsong v1.0.0

allonlytrumpetsong.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using ExitGames.Client.Photon;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using Photon.Realtime;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[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 Kilian.TrumpetPlaylists
{
	[BepInPlugin("kilian.peak.trumpetplaylists", "allonlytrumpetsong", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		private sealed class Song
		{
			public string Name;

			public string Hash;

			public AudioClip Clip;
		}

		private sealed class Pack
		{
			public string Name;

			public List<Song> Songs = new List<Song>();
		}

		private sealed class State
		{
			public int Pack;

			public int Track;

			public AudioSource Source;

			public AudioSource Original;

			public bool WasMuted;

			public bool Muted;

			public bool WasHeld;
		}

		public const string Id = "kilian.peak.trumpetplaylists";

		private const byte EventCode = 175;

		private static Plugin instance;

		private Harmony harmony;

		private readonly List<Pack> packs = new List<Pack>();

		private readonly Dictionary<BugleSFX, State> states = new Dictionary<BugleSFX, State>();

		private bool ready;

		private string notice = "";

		private float noticeUntil;

		private float syncAt;

		private BugleSFX noticeOwner;

		private GUIStyle noticeStyle;

		private bool noticeIsControls;

		private string PackName(string folder)
		{
			DirectoryInfo directoryInfo = new DirectoryInfo(folder);
			int num = 0;
			while (directoryInfo != null && num < 3 && !string.Equals(directoryInfo.FullName, Path.GetFullPath(Paths.PluginPath), StringComparison.OrdinalIgnoreCase))
			{
				string path = Path.Combine(directoryInfo.FullName, "manifest.json");
				if (File.Exists(path))
				{
					try
					{
						Match match = Regex.Match(File.ReadAllText(path), "\\\"name\\\"\\s*:\\s*\\\"([A-Za-z0-9_]+)\\\"");
						if (match.Success)
						{
							return match.Groups[1].Value;
						}
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Cannot read pack manifest: " + ex.Message));
					}
				}
				num++;
				directoryInfo = directoryInfo.Parent;
			}
			DirectoryInfo directoryInfo2 = new DirectoryInfo(folder);
			if (!(directoryInfo2.Name == "OnlyTrumpetSongs") || directoryInfo2.Parent == null)
			{
				return directoryInfo2.Name;
			}
			return directoryInfo2.Parent.Name;
		}

		private void Awake()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected O, but got Unknown
			instance = this;
			harmony = new Harmony("kilian.peak.trumpetplaylists");
			if (Chainloader.PluginInfos.TryGetValue("OnlyTrumpetSongs", out var value))
			{
				Type type = ((object)value.Instance).GetType();
				if (type.FullName != "OnlyTrumpetSongs" || value.Metadata.Version.ToString() != "1.1.2")
				{
					((BaseUnityPlugin)this).Logger.LogError((object)"Unsupported OnlyTrumpetSongs version. Manager disabled to preserve original behavior.");
					((Behaviour)this).enabled = false;
					return;
				}
				((MonoBehaviour)value.Instance).StopAllCoroutines();
				((Behaviour)value.Instance).enabled = false;
				MethodBase[] array = Harmony.GetAllPatchedMethods().ToArray();
				foreach (MethodBase methodBase in array)
				{
					Patches patchInfo = Harmony.GetPatchInfo(methodBase);
					Patch[] array2 = (from p in patchInfo.Prefixes.Concat(patchInfo.Postfixes)
						where p.owner == "OnlyTrumpetSongs" && p.PatchMethod.DeclaringType.Assembly == type.Assembly
						select p).ToArray();
					foreach (Patch val in array2)
					{
						harmony.Unpatch(methodBase, val.PatchMethod);
					}
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)"OnlyTrumpetSongs 1.1.2 audio control replaced; installed sound packs retained.");
			}
			harmony.Patch((MethodBase)AccessTools.Method(typeof(BugleSFX), "Update", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "AfterBugle", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			PhotonNetwork.NetworkingClient.EventReceived += Receive;
			((MonoBehaviour)this).StartCoroutine(Load());
		}

		private IEnumerator Load()
		{
			SortedDictionary<string, string> sortedDictionary = new SortedDictionary<string, string>(StringComparer.Ordinal);
			string[] files = Directory.GetFiles(Paths.PluginPath, "com.github.ChuMenschis.OnlyTrumpetSongs.dll", SearchOption.AllDirectories);
			for (int i = 0; i < files.Length; i++)
			{
				string directoryName = Path.GetDirectoryName(files[i]);
				string text = Path.Combine(directoryName, "Sounds");
				if (Directory.Exists(text))
				{
					string value = PackName(directoryName);
					sortedDictionary[text] = value;
				}
			}
			string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "Playlists");
			if (Directory.Exists(path))
			{
				files = Directory.GetDirectories(path);
				foreach (string text2 in files)
				{
					sortedDictionary[text2] = Path.GetFileName(text2);
				}
			}
			foreach (KeyValuePair<string, string> item in sortedDictionary)
			{
				Pack pack = new Pack
				{
					Name = item.Value
				};
				foreach (string file in Directory.GetFiles(item.Key).OrderBy<string, string>((string f) => f, StringComparer.Ordinal))
				{
					string text3 = Path.GetExtension(file).ToLowerInvariant();
					if (text3 != ".ogg" && text3 != ".wav")
					{
						continue;
					}
					string hash;
					try
					{
						using SHA256 sHA = SHA256.Create();
						using FileStream inputStream = File.OpenRead(file);
						hash = BitConverter.ToString(sHA.ComputeHash(inputStream)).Replace("-", "");
					}
					catch (Exception ex)
					{
						((BaseUnityPlugin)this).Logger.LogWarning((object)("Cannot read " + file + ": " + ex.Message));
						continue;
					}
					UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(new Uri(Path.GetFullPath(file)).AbsoluteUri, (AudioType)((text3 == ".ogg") ? 14 : 20));
					try
					{
						yield return request.SendWebRequest();
						if ((int)request.result != 1)
						{
							((BaseUnityPlugin)this).Logger.LogWarning((object)("Audio load failed: " + file + " " + request.error));
							continue;
						}
						AudioClip val = null;
						try
						{
							val = DownloadHandlerAudioClip.GetContent(request);
						}
						catch (Exception ex2)
						{
							((BaseUnityPlugin)this).Logger.LogWarning((object)ex2.Message);
						}
						if (Object.op_Implicit((Object)(object)val))
						{
							((Object)val).name = Path.GetFileNameWithoutExtension(file);
							pack.Songs.Add(new Song
							{
								Name = ((Object)val).name,
								Hash = hash,
								Clip = val
							});
						}
					}
					finally
					{
						((IDisposable)request)?.Dispose();
					}
					hash = null;
				}
				if (pack.Songs.Count > 0)
				{
					packs.Add(pack);
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Playlist " + pack.Name + ": " + pack.Songs.Count + " tracks"));
				}
			}
			ready = true;
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Ready: " + packs.Count + " playlists. Every object starts in Original mode."));
		}

		private static void AfterBugle(BugleSFX __instance)
		{
			if (Object.op_Implicit((Object)(object)instance) && ((Behaviour)instance).enabled)
			{
				instance.Tick(__instance);
			}
		}

		private State Get(BugleSFX b)
		{
			if (!states.TryGetValue(b, out var value))
			{
				value = (states[b] = new State());
			}
			return value;
		}

		private void Tick(BugleSFX b)
		{
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Invalid comparison between Unknown and I4
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			if (!ready || !Object.op_Implicit((Object)(object)b) || !Object.op_Implicit((Object)(object)b.buglePlayer))
			{
				return;
			}
			State state = Get(b);
			PhotonView component = ((Component)b).GetComponent<PhotonView>();
			Item component2 = ((Component)b).GetComponent<Item>();
			bool flag = Object.op_Implicit((Object)(object)component) && component.IsMine && Object.op_Implicit((Object)(object)component2) && (int)component2.itemState == 1;
			if (flag && !state.WasHeld)
			{
				Show(b, "Ctrl + wheel: playlist   |   Wheel: track", controls: true);
			}
			state.WasHeld = flag;
			if (flag && (int)Cursor.lockState == 1)
			{
				float y = Input.mouseScrollDelta.y;
				if (Math.Abs(y) > 0.01f)
				{
					int direction = ((y > 0f) ? 1 : (-1));
					bool flag2 = Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305);
					int pack = state.Pack;
					int track = state.Track;
					Selection.Change(ref state.Pack, ref state.Track, direction, flag2, packs.Select((Pack p) => p.Songs.Count).ToArray());
					if (flag2 && state.Pack != pack)
					{
						Show(b, (state.Pack == 0) ? "Original" : packs[state.Pack - 1].Name);
					}
					else if (!flag2 && state.Pack > 0 && state.Track != track)
					{
						Show(b, packs[state.Pack - 1].Songs[state.Track].Name);
					}
					if (flag2 || state.Pack > 0)
					{
						Send(b, state);
					}
				}
			}
			Apply(b, state);
		}

		private void Apply(BugleSFX b, State s)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			if (s.Pack == 0)
			{
				Restore(s);
				return;
			}
			if (!Object.op_Implicit((Object)(object)s.Source))
			{
				AudioSource buglePlayer = b.buglePlayer;
				s.Source = ((Component)b).gameObject.AddComponent<AudioSource>();
				s.Source.playOnAwake = false;
				s.Source.loop = true;
				s.Source.outputAudioMixerGroup = buglePlayer.outputAudioMixerGroup;
				s.Source.spatialBlend = buglePlayer.spatialBlend;
				s.Source.rolloffMode = buglePlayer.rolloffMode;
				s.Source.minDistance = buglePlayer.minDistance;
				s.Source.maxDistance = buglePlayer.maxDistance;
				s.Source.dopplerLevel = buglePlayer.dopplerLevel;
				s.Source.spread = buglePlayer.spread;
			}
			if ((Object)(object)s.Original != (Object)(object)b.buglePlayer)
			{
				Restore(s);
				s.Original = b.buglePlayer;
			}
			if (!s.Muted)
			{
				s.WasMuted = s.Original.mute;
				s.Muted = true;
			}
			s.Original.mute = true;
			AudioClip clip = packs[s.Pack - 1].Songs[s.Track].Clip;
			if ((Object)(object)s.Source.clip != (Object)(object)clip)
			{
				s.Source.Stop();
				s.Source.clip = clip;
			}
			s.Source.volume = b.buglePlayer.volume;
			s.Source.pitch = 1f;
			if (b.hold && ((Behaviour)b).isActiveAndEnabled)
			{
				if (!s.Source.isPlaying)
				{
					s.Source.Play();
				}
			}
			else
			{
				s.Source.Stop();
			}
		}

		private void Restore(State s)
		{
			if (Object.op_Implicit((Object)(object)s.Source))
			{
				s.Source.Stop();
			}
			if (s.Muted && Object.op_Implicit((Object)(object)s.Original))
			{
				s.Original.mute = s.WasMuted;
			}
			s.Muted = false;
		}

		private void Send(BugleSFX b, State s)
		{
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d7: Expected O, but got Unknown
			PhotonView component = ((Component)b).GetComponent<PhotonView>();
			if (PhotonNetwork.InRoom && Object.op_Implicit((Object)(object)component) && component.IsMine)
			{
				PhotonNetwork.RaiseEvent((byte)175, (object)new object[6]
				{
					"kilian.peak.trumpetplaylists",
					1,
					component.ViewID,
					Array.IndexOf(((Component)b).GetComponents<BugleSFX>(), b),
					(s.Pack == 0) ? "" : packs[s.Pack - 1].Name,
					(s.Pack == 0) ? "" : packs[s.Pack - 1].Songs[s.Track].Hash
				}, new RaiseEventOptions
				{
					Receivers = (ReceiverGroup)0
				}, SendOptions.SendReliable);
			}
		}

		private void Receive(EventData e)
		{
			if (!ready || e.Code != 175 || !(e.CustomData is object[] array) || array.Length != 6 || !(array[0] is string text) || text != "kilian.peak.trumpetplaylists" || !(array[1] is int num) || num != 1 || !(array[2] is int num2) || !(array[3] is int num3))
			{
				return;
			}
			object obj = array[4];
			string pack = obj as string;
			if (pack == null)
			{
				return;
			}
			obj = array[5];
			string hash = obj as string;
			if (hash == null)
			{
				return;
			}
			PhotonView val = PhotonView.Find(num2);
			if (!Object.op_Implicit((Object)(object)val) || val.OwnerActorNr != e.Sender || val.IsMine)
			{
				return;
			}
			BugleSFX[] components = ((Component)val).GetComponents<BugleSFX>();
			if (num3 < 0 || num3 >= components.Length)
			{
				return;
			}
			State state = Get(components[num3]);
			state.Pack = 0;
			state.Track = 0;
			if (pack != "")
			{
				int num4 = packs.FindIndex((Pack x) => x.Name == pack);
				int num5 = ((num4 < 0) ? (-1) : packs[num4].Songs.FindIndex((Song x) => x.Hash == hash));
				if (num5 >= 0)
				{
					state.Pack = num4 + 1;
					state.Track = num5;
				}
			}
			Apply(components[num3], state);
		}

		private void Update()
		{
			KeyValuePair<BugleSFX, State>[] array = states.ToArray();
			for (int i = 0; i < array.Length; i++)
			{
				KeyValuePair<BugleSFX, State> keyValuePair = array[i];
				if (!Object.op_Implicit((Object)(object)keyValuePair.Key))
				{
					Restore(keyValuePair.Value);
					if (Object.op_Implicit((Object)(object)keyValuePair.Value.Source))
					{
						Object.Destroy((Object)(object)keyValuePair.Value.Source);
					}
					states.Remove(keyValuePair.Key);
				}
				else if (!((Behaviour)keyValuePair.Key).isActiveAndEnabled)
				{
					Restore(keyValuePair.Value);
					keyValuePair.Value.WasHeld = false;
				}
			}
			if (!ready || !(Time.unscaledTime >= syncAt))
			{
				return;
			}
			syncAt = Time.unscaledTime + 5f;
			foreach (KeyValuePair<BugleSFX, State> state in states)
			{
				Send(state.Key, state.Value);
			}
		}

		private void Show(BugleSFX owner, string message, bool controls = false)
		{
			noticeIsControls = controls;
			noticeOwner = owner;
			notice = message;
			noticeUntil = Time.unscaledTime + 4f;
		}

		private void OnGUI()
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Invalid comparison between Unknown and I4
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Invalid comparison between Unknown and I4
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Expected O, but got Unknown
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Expected O, but got Unknown
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Expected O, but got Unknown
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0222: Unknown result type (might be due to invalid IL or missing references)
			//IL_0252: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime >= noticeUntil || !Object.op_Implicit((Object)(object)noticeOwner) || !((Behaviour)noticeOwner).isActiveAndEnabled || (int)Cursor.lockState != 1)
			{
				return;
			}
			Item component = ((Component)noticeOwner).GetComponent<Item>();
			PhotonView component2 = ((Component)noticeOwner).GetComponent<PhotonView>();
			if (!Object.op_Implicit((Object)(object)component) || (int)component.itemState != 1 || !Object.op_Implicit((Object)(object)component2) || !component2.IsMine)
			{
				return;
			}
			if (noticeStyle == null)
			{
				noticeStyle = new GUIStyle(GUI.skin.box)
				{
					alignment = (TextAnchor)4,
					wordWrap = true,
					richText = false,
					fontStyle = (FontStyle)1
				};
			}
			float num = Mathf.Clamp((float)Screen.height / 1080f, 0.75f, 4f);
			noticeStyle.fontSize = Mathf.RoundToInt((float)(noticeIsControls ? 18 : 24) * num);
			noticeStyle.fontStyle = (FontStyle)(!noticeIsControls);
			noticeStyle.normal.textColor = Color.white;
			noticeStyle.padding = new RectOffset(Mathf.RoundToInt(18f * num), Mathf.RoundToInt(18f * num), Mathf.RoundToInt(10f * num), Mathf.RoundToInt(10f * num));
			GUIContent val = new GUIContent(notice);
			noticeStyle.wordWrap = !noticeIsControls;
			float num2 = (float)Screen.width * 0.85f;
			if (noticeIsControls)
			{
				while (noticeStyle.fontSize > 1 && noticeStyle.CalcSize(val).x + 4f * num > num2)
				{
					GUIStyle obj = noticeStyle;
					int fontSize = obj.fontSize;
					obj.fontSize = fontSize - 1;
				}
			}
			float num3 = Mathf.Min(num2, Mathf.Max(320f * num, noticeStyle.CalcSize(val).x + (noticeIsControls ? (4f * num) : 0f)));
			float num4 = (noticeIsControls ? noticeStyle.CalcSize(val).y : noticeStyle.CalcHeight(val, num3));
			GUI.Box(new Rect(((float)Screen.width - num3) / 2f, (float)Screen.height - 120f * num - num4, num3, num4), val, noticeStyle);
		}

		private void OnDestroy()
		{
			PhotonNetwork.NetworkingClient.EventReceived -= Receive;
			foreach (State value in states.Values)
			{
				Restore(value);
				if (Object.op_Implicit((Object)(object)value.Source))
				{
					Object.Destroy((Object)(object)value.Source);
				}
			}
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			foreach (Pack pack in packs)
			{
				foreach (Song song in pack.Songs)
				{
					if (Object.op_Implicit((Object)(object)song.Clip))
					{
						Object.Destroy((Object)(object)song.Clip);
					}
				}
			}
			instance = null;
		}
	}
	public static class Selection
	{
		public static int Wrap(int value, int count)
		{
			if (count > 0)
			{
				return (value % count + count) % count;
			}
			return 0;
		}

		public static void Change(ref int pack, ref int track, int direction, bool control, int[] counts)
		{
			if (control)
			{
				pack = Wrap(pack + direction, counts.Length + 1);
				track = 0;
			}
			else if (pack > 0 && pack <= counts.Length)
			{
				track = Wrap(track + direction, counts[pack - 1]);
			}
		}
	}
}