Decompiled source of AutoReload v1.0.0

plugins/com.github.Hamunii.AutoReload.dll

Decompiled 4 months 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.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("com.github.Hamunii.AutoReload")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+c8f9a8a0cb342cc63edbe95ecef3cb958b50f7fc")]
[assembly: AssemblyProduct("com.github.Hamunii.AutoReload")]
[assembly: AssemblyTitle("AutoReload")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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 BepInEx
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class BepInAutoPluginAttribute : Attribute
	{
		public BepInAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace BepInEx.Preloader.Core.Patching
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
	[Conditional("CodeGeneration")]
	internal sealed class PatcherAutoPluginAttribute : Attribute
	{
		public PatcherAutoPluginAttribute(string? id = null, string? name = null, string? version = null)
		{
		}
	}
}
namespace AutoReload
{
	[BepInPlugin("com.github.Hamunii.AutoReload", "AutoReload", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private static readonly string dumpedAssembliesPath = Path.Combine(Paths.BepInExRootPath, "AutoReloadDumpedAssemblies");

		private static DefaultAssemblyResolver defaultResolver = null;

		private static FileSystemWatcher fileSystemWatcher = null;

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

		public const string Id = "com.github.Hamunii.AutoReload";

		private static ConfigEntry<bool> QuietMode { get; set; } = null;


		public static string Name => "AutoReload";

		public static string Version => "1.0.0";

		private void Awake()
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			defaultResolver = new DefaultAssemblyResolver();
			((BaseAssemblyResolver)defaultResolver).AddSearchDirectory(Paths.PluginPath);
			((BaseAssemblyResolver)defaultResolver).AddSearchDirectory(Paths.ManagedPath);
			((BaseAssemblyResolver)defaultResolver).AddSearchDirectory(Paths.BepInExAssemblyDirectory);
			QuietMode = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "QuietMode", false, new ConfigDescription("Disable all logging except for error messages.", (AcceptableValueBase)null, Array.Empty<object>()));
			if (Directory.Exists(dumpedAssembliesPath))
			{
				Directory.Delete(dumpedAssembliesPath, recursive: true);
			}
			StartFileSystemWatcher();
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Plugin " + Name + " is loaded!"));
		}

		private void StartFileSystemWatcher()
		{
			fileSystemWatcher = new FileSystemWatcher(Paths.PluginPath)
			{
				IncludeSubdirectories = true,
				NotifyFilter = NotifyFilters.LastWrite,
				Filter = "*.dll"
			};
			fileSystemWatcher.Changed += FileChangedEventHandler;
			fileSystemWatcher.Created += FileChangedEventHandler;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		private void FileChangedEventHandler(object sender, FileSystemEventArgs args)
		{
			if (!QuietMode.Value)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)("File '" + Path.GetFileName(args.Name) + "' changed."));
			}
			LoadPlugin(args.FullPath);
		}

		private void UnloadPlugin(string path)
		{
			if (pathToId.TryGetValue(path, out string value) && Chainloader.PluginInfos.TryGetValue(value, out var value2))
			{
				Chainloader.PluginInfos.Remove(value);
				Object.Destroy((Object)(object)value2.Instance);
			}
		}

		private void LoadPlugin(string path)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Expected O, but got Unknown
			string path2 = path;
			if (!File.Exists(path2))
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)("File at '" + path2 + "' has been deleted."));
				return;
			}
			AssemblyDefinition val = AssemblyDefinition.ReadAssembly(path2, new ReaderParameters
			{
				AssemblyResolver = (IAssemblyResolver)(object)defaultResolver,
				ReadSymbols = true
			});
			try
			{
				((AssemblyNameReference)val.Name).Name = $"{((AssemblyNameReference)val.Name).Name}-{DateTime.Now.Ticks}";
				if (!Directory.Exists(dumpedAssembliesPath))
				{
					Directory.CreateDirectory(dumpedAssembliesPath);
				}
				string text = Path.Combine(dumpedAssembliesPath, ((AssemblyNameReference)val.Name).Name + Path.GetExtension(((ModuleReference)val.MainModule).Name));
				using (FileStream fileStream = new FileStream(text, FileMode.Create))
				{
					val.Write((Stream)fileStream, new WriterParameters
					{
						WriteSymbols = true
					});
				}
				Assembly ass = Assembly.LoadFile(text);
				if (!QuietMode.Value)
				{
					((BaseUnityPlugin)this).Logger.Log((LogLevel)16, (object)("Loaded dumped Assembly from '" + text + "'"));
				}
				foreach (Type type in GetTypesSafe(ass))
				{
					try
					{
						if (!typeof(BaseUnityPlugin).IsAssignableFrom(type))
						{
							continue;
						}
						BepInPlugin metadata = MetadataHelper.GetMetadata(type);
						if (metadata == null)
						{
							continue;
						}
						pathToId[path2] = metadata.GUID;
						UnloadPlugin(path2);
						TypeDefinition val2 = ((IEnumerable<TypeDefinition>)val.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).FullName == type.FullName);
						PluginInfo pluginInfo = Chainloader.ToPluginInfo(val2);
						((MonoBehaviour)this).StartCoroutine(DelayAction(delegate
						{
							//IL_0089: Unknown result type (might be due to invalid IL or missing references)
							//IL_008f: Expected O, but got Unknown
							if (!QuietMode.Value)
							{
								((BaseUnityPlugin)this).Logger.Log((LogLevel)16, (object)$"Loading [{metadata.Name} {metadata.Version}]");
							}
							try
							{
								Chainloader.PluginInfos[metadata.GUID] = pluginInfo;
								BaseUnityPlugin value = (BaseUnityPlugin)((Component)this).gameObject.AddComponent(type);
								Traverse val3 = Traverse.Create((object)pluginInfo);
								val3.Property<BaseUnityPlugin>("Instance", (object[])null).Value = value;
								val3.Property<string>("Location", (object[])null).Value = path2;
							}
							catch (Exception arg2)
							{
								((BaseUnityPlugin)this).Logger.LogError((object)$"Failed to load plugin {metadata.GUID} because of exception: {arg2}");
								Chainloader.PluginInfos.Remove(metadata.GUID);
							}
						}));
					}
					catch (Exception arg)
					{
						((BaseUnityPlugin)this).Logger.LogError((object)$"Failed to load plugin {type.Name} because of exception: {arg}");
					}
				}
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		private IEnumerable<Type> GetTypesSafe(Assembly ass)
		{
			try
			{
				return ass.GetTypes();
			}
			catch (ReflectionTypeLoadException ex)
			{
				return ex.Types.Where((Type x) => (object)x != null);
			}
		}

		private IEnumerator DelayAction(Action action)
		{
			yield return null;
			action();
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}