Decompiled source of EchoLoader v0.1.0

BepInEx/patchers/EchoLoader/me.loaforc.soundapi.echo.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading.Tasks;
using BepInEx;
using BepInEx.Logging;
using CustomSounds;
using HarmonyLib;
using LCSoundTool;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using UnityEngine;
using loaforcsSoundAPI.Core.JSON;
using loaforcsSoundAPI.Echo.Data;
using loaforcsSoundAPI.Echo.Patches;
using loaforcsSoundAPI.Reporting;
using loaforcsSoundAPI.Reporting.Data;
using loaforcsSoundAPI.SoundPacks.Data;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("CustomSounds")]
[assembly: IgnoresAccessChecksTo("LC_SoundTool")]
[assembly: AssemblyCompany("me.loaforc.soundapi.echo")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+bd777abb93b9760288f158b8740f43a76045e8aa")]
[assembly: AssemblyProduct("loaforcsSoundAPI-Echo")]
[assembly: AssemblyTitle("me.loaforc.soundapi.echo")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[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 loaforcsSoundAPI.Echo
{
	internal static class CustomSoundsLoadPipeline
	{
		internal static List<SoundPack> CustomSoundsPacks { get; private set; } = new List<SoundPack>();


		internal static long LoadTime { get; private set; }

		internal static void StartPipeline()
		{
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Expected O, but got Unknown
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			Stopwatch stopwatch = Stopwatch.StartNew();
			EchoPreloader.Logger.LogInfo((object)"Starting CustomSounds Sound-Pack loading pipeline.");
			List<string> list = FindCustomSoundsSoundPacks();
			EchoPreloader.Logger.LogInfo((object)$"Found '{list.Count}' sound-pack(s) to load from CustomSounds!");
			foreach (string item in list)
			{
				ThunderstoreManifest thunderstoreManifest = JSONDataLoader.LoadFromFile<ThunderstoreManifest>(Path.Combine(item, "manifest.json"));
				SoundPack pack = new SoundPack(thunderstoreManifest.Name, item);
				SoundReplacementCollection parent = new SoundReplacementCollection(pack);
				EchoPreloader.Logger.LogInfo((object)("Loading Sound-Pack: " + pack.Name));
				PopulateSoundReplacementCollection(parent, Path.Combine(item, "CustomSounds")).ContinueWith(delegate
				{
					EchoPreloader.Logger.LogInfo((object)("CustomSounds pack " + pack.Name + " is done"));
					SoundAPI.RegisterSoundPack(pack);
					CustomSoundsPacks.Add(pack);
				});
			}
			stopwatch.Stop();
			LoadTime = stopwatch.ElapsedMilliseconds;
			EchoPreloader.Logger.LogInfo((object)$"All done! Took {LoadTime}ms :3");
		}

		private static async Task PopulateSoundReplacementCollection(SoundReplacementCollection parent, string path)
		{
			string[] files = Directory.GetFiles(path, "*.wav", SearchOption.TopDirectoryOnly);
			foreach (string audioFile in files)
			{
				AudioClip val = await SoundAPI.LoadAudioFileAsync(audioFile);
				(string clipName, int weight) tuple = ParseFileName(Path.GetFileNameWithoutExtension(audioFile));
				string item = tuple.clipName;
				int item2 = tuple.weight;
				SoundReplacementGroup val2 = new SoundReplacementGroup(parent, new List<string>(1) { "*:*:" + item });
				new SoundInstance(val2, item2, val);
			}
			files = Directory.GetDirectories(path);
			foreach (string path2 in files)
			{
				string audioFile = "*";
				string fileName = Path.GetFileName(path2);
				EchoPreloader.Logger.LogDebug((object)("directoryName: " + fileName));
				if (fileName.EndsWith("-AS"))
				{
					audioFile = fileName.Substring(0, fileName.Length - 3);
				}
				EchoPreloader.Logger.LogDebug((object)("sourceObjectNameMatch: " + audioFile));
				string[] files2 = Directory.GetFiles(path2, "*.wav", SearchOption.TopDirectoryOnly);
				foreach (string audioFile2 in files2)
				{
					AudioClip val3 = await SoundAPI.LoadAudioFileAsync(audioFile2);
					(string clipName, int weight) tuple2 = ParseFileName(Path.GetFileNameWithoutExtension(audioFile2));
					string item3 = tuple2.clipName;
					int item4 = tuple2.weight;
					SoundReplacementGroup val4 = new SoundReplacementGroup(parent, new List<string>(1) { "*:" + audioFile + ":" + item3 });
					new SoundInstance(val4, item4, val3);
				}
			}
		}

		private static List<string> FindCustomSoundsSoundPacks()
		{
			return (from modFolder in Directory.GetDirectories(Paths.PluginPath)
				where Directory.Exists(Path.Combine(modFolder, "CustomSounds"))
				select modFolder).ToList();
		}

		private static (string clipName, int weight) ParseFileName(string fileName)
		{
			string[] array = fileName.Split("-");
			if (!int.TryParse(array.Last(), out var result))
			{
				result = 1;
			}
			return (array[0], result);
		}
	}
	public static class EchoPreloader
	{
		internal static bool CustomSoundsPatched = false;

		internal static bool SoundToolPatched = false;

		private static Harmony _harmony = null;

		public static IEnumerable<string> TargetDLLs { get; } = Array.Empty<string>();


		internal static ManualLogSource Logger { get; } = Logger.CreateLogSource("me.loaforc.soundapi.echo");


		public static void Patch(AssemblyDefinition assembly)
		{
		}

		public static void Finish()
		{
			Logger.LogInfo((object)"Loading Echo v0.1.0");
			Logger.LogInfo((object)"Running patches.");
			_harmony = Harmony.CreateAndPatchAll(Assembly.GetExecutingAssembly(), "me.loaforc.soundapi.echo");
			AppDomain.CurrentDomain.AssemblyLoad += delegate(object sender, AssemblyLoadEventArgs e)
			{
				if (e.LoadedAssembly.GetName().Name == "CustomSounds" && !CustomSoundsPatched)
				{
					Logger.LogInfo((object)"Attempting to patch CustomSounds.");
					TryRunPatches(typeof(CustomSoundsPatches), ref CustomSoundsPatched);
				}
				if (e.LoadedAssembly.GetName().Name == "LC_SoundTool" && !SoundToolPatched)
				{
					Logger.LogInfo((object)"Attempting to patch LCSoundTool.");
					TryRunPatches(typeof(SoundToolPatches), ref SoundToolPatched);
				}
			};
			Logger.LogInfo((object)"Finished loading :3");
		}

		internal static void AddReportSection()
		{
			SoundReportHandler.AddReportSection("Echo Loader", (Action<StreamWriter, SoundReport>)delegate(StreamWriter stream, SoundReport _)
			{
				stream.WriteLine("Echo version: `0.1.0` <br/><br/>");
				stream.WriteLine($"Patched CustomSounds: `{CustomSoundsPatched}` <br/>");
				stream.WriteLine($"Patched LCSoundTool: `{SoundToolPatched}` <br/>");
				stream.WriteLine($"Load time: `{CustomSoundsLoadPipeline.LoadTime}ms`");
				SoundReportHandler.WriteList("CustomSounds packs", stream, (ICollection<string>)CustomSoundsLoadPipeline.CustomSoundsPacks.Select((SoundPack it) => it.Name).ToList());
			});
		}

		internal static void TryRunPatches(Type patchHandler, ref bool result)
		{
			try
			{
				_harmony.PatchAll(patchHandler);
				Logger.LogInfo((object)"patched");
				result = true;
			}
			catch (TypeLoadException)
			{
				Logger.LogInfo((object)"Failed this time, but echo will still work.");
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "me.loaforc.soundapi.echo";

		public const string PLUGIN_NAME = "loaforcsSoundAPI-Echo";

		public const string PLUGIN_VERSION = "0.1.0";
	}
}
namespace loaforcsSoundAPI.Echo.Patches
{
	internal static class CustomSoundsPatches
	{
		[HarmonyTranspiler]
		[HarmonyPatch(typeof(Plugin), "Awake")]
		[HarmonyPatch(typeof(Plugin), "Start")]
		[HarmonyPatch(typeof(Plugin), "OnDestroy")]
		[HarmonyPatch(typeof(Plugin), "Initialize")]
		private static IEnumerable<CodeInstruction> DisableCustomSounds(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().Insert((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ret, (object)null)
			}).InstructionEnumeration();
		}
	}
	[HarmonyPatch(typeof(Logger))]
	internal static class LoggerPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("LogMessage")]
		private static void RunPipeline(object data)
		{
			if (data is string text && text == "Chainloader startup complete")
			{
				CustomSoundsLoadPipeline.StartPipeline();
				EchoPreloader.AddReportSection();
			}
		}
	}
	internal static class SoundToolPatches
	{
		[HarmonyTranspiler]
		[HarmonyPatch(typeof(SoundTool), "Awake")]
		[HarmonyPatch(typeof(SoundTool), "Start")]
		[HarmonyPatch(typeof(SoundTool), "Update")]
		[HarmonyPatch(typeof(SoundTool), "OnDestroy")]
		private static IEnumerable<CodeInstruction> DisableSoundTool(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			return new CodeMatcher(instructions, (ILGenerator)null).Start().Insert((CodeInstruction[])(object)new CodeInstruction[1]
			{
				new CodeInstruction(OpCodes.Ret, (object)null)
			}).InstructionEnumeration();
		}
	}
}
namespace loaforcsSoundAPI.Echo.Data
{
	internal class ThunderstoreManifest
	{
		public string Name { get; private set; }
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}