You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
10 KiB

6 years ago
6 years ago
6 years ago
  1. using IllusionInjector.Logging;
  2. using IllusionInjector.Updating;
  3. using IllusionInjector.Utilities;
  4. using IllusionPlugin;
  5. using IllusionPlugin.BeatSaber;
  6. using Mono.Cecil;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Diagnostics;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.InteropServices;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using LoggerBase = IllusionPlugin.Logging.Logger;
  18. namespace IllusionInjector
  19. {
  20. public static class PluginManager
  21. {
  22. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  23. public class BSPluginMeta
  24. {
  25. public IBeatSaberPlugin Plugin { get; internal set; }
  26. public string Filename { get; internal set; }
  27. public ModsaberModInfo ModsaberInfo { get; internal set; }
  28. }
  29. public static IEnumerable<IBeatSaberPlugin> BSPlugins
  30. {
  31. get
  32. {
  33. if(_bsPlugins == null)
  34. {
  35. LoadPlugins();
  36. }
  37. return _bsPlugins.Select(p => p.Plugin);
  38. }
  39. }
  40. private static List<BSPluginMeta> _bsPlugins = null;
  41. internal static IEnumerable<BSPluginMeta> BSMetas
  42. {
  43. get
  44. {
  45. if (_bsPlugins == null)
  46. {
  47. LoadPlugins();
  48. }
  49. return _bsPlugins;
  50. }
  51. }
  52. public static IEnumerable<IPlugin> Plugins
  53. {
  54. get
  55. {
  56. if (_ipaPlugins == null)
  57. {
  58. LoadPlugins();
  59. }
  60. return _ipaPlugins;
  61. }
  62. }
  63. private static List<IPlugin> _ipaPlugins = null;
  64. private static void LoadPlugins()
  65. {
  66. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  67. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  68. // so we need to resort to P/Invoke
  69. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  70. Logger.log.Info(exeName);
  71. _bsPlugins = new List<BSPluginMeta>();
  72. _ipaPlugins = new List<IPlugin>();
  73. if (!Directory.Exists(pluginDirectory)) return;
  74. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  75. if (!Directory.Exists(cacheDir))
  76. {
  77. Directory.CreateDirectory(cacheDir);
  78. }
  79. else
  80. {
  81. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  82. {
  83. File.Delete(plugin);
  84. }
  85. }
  86. //Copy plugins to .cache
  87. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  88. foreach (string s in originalPlugins)
  89. {
  90. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  91. File.Copy(Path.Combine(pluginDirectory, s), pluginCopy);
  92. }
  93. var selfPlugin = new BSPluginMeta
  94. {
  95. Filename = Path.Combine(Environment.CurrentDirectory, "IPA.exe"),
  96. Plugin = new SelfPlugin()
  97. };
  98. selfPlugin.ModsaberInfo = selfPlugin.Plugin.ModInfo;
  99. _bsPlugins.Add(selfPlugin);
  100. //Load copied plugins
  101. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  102. foreach (string s in copiedPlugins)
  103. {
  104. var result = LoadPluginsFromFile(s, exeName);
  105. _bsPlugins.AddRange(result.Item1);
  106. _ipaPlugins.AddRange(result.Item2);
  107. }
  108. // DEBUG
  109. Logger.log.Info($"Running on Unity {UnityEngine.Application.unityVersion}");
  110. Logger.log.Info($"Game version {UnityEngine.Application.version}");
  111. Logger.log.Info("-----------------------------");
  112. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  113. Logger.log.Info("-----------------------------");
  114. foreach (var plugin in _bsPlugins)
  115. {
  116. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  117. }
  118. Logger.log.Info("-----------------------------");
  119. foreach (var plugin in _ipaPlugins)
  120. {
  121. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  122. }
  123. Logger.log.Info("-----------------------------");
  124. }
  125. private static Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file, string exeName)
  126. {
  127. List<BSPluginMeta> bsPlugins = new List<BSPluginMeta>();
  128. List<IPlugin> ipaPlugins = new List<IPlugin>();
  129. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  130. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  131. T OptionalGetPlugin<T>(Type t) where T : class
  132. {
  133. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  134. if (t.GetInterface(typeof(T).Name) != null)
  135. {
  136. try
  137. {
  138. T pluginInstance = Activator.CreateInstance(t) as T;
  139. string[] filter = null;
  140. if (pluginInstance is IGenericEnhancedPlugin)
  141. {
  142. filter = ((IGenericEnhancedPlugin)pluginInstance).Filter;
  143. }
  144. if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  145. return pluginInstance;
  146. }
  147. catch (Exception e)
  148. {
  149. Logger.log.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  150. }
  151. }
  152. return null;
  153. }
  154. try
  155. {
  156. var module = ModuleDefinition.ReadModule(file);
  157. bool modifiedModule = false;
  158. foreach (var @ref in module.AssemblyReferences)
  159. {
  160. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  161. {
  162. @ref.Name = "IPA.Loader";
  163. modifiedModule = true;
  164. }
  165. }
  166. if (modifiedModule) module.Write(file);
  167. Assembly assembly = Assembly.LoadFrom(file);
  168. foreach (Type t in assembly.GetTypes())
  169. {
  170. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  171. if (bsPlugin != null)
  172. {
  173. try
  174. {
  175. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  176. if (init != null)
  177. {
  178. var initArgs = new List<object>();
  179. var initParams = init.GetParameters();
  180. LoggerBase modLogger = null;
  181. IModPrefs modPrefs = null;
  182. foreach (var param in initParams)
  183. {
  184. var ptype = param.ParameterType;
  185. if (ptype.IsAssignableFrom(typeof(LoggerBase))) {
  186. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  187. initArgs.Add(modLogger);
  188. }
  189. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  190. {
  191. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  192. initArgs.Add(modPrefs);
  193. }
  194. else
  195. initArgs.Add(ptype.GetDefault());
  196. }
  197. init.Invoke(bsPlugin, initArgs.ToArray());
  198. }
  199. bsPlugins.Add(new BSPluginMeta
  200. {
  201. Plugin = bsPlugin,
  202. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  203. ModsaberInfo = bsPlugin.ModInfo
  204. });
  205. }
  206. catch (AmbiguousMatchException)
  207. {
  208. Logger.log.Error($"Only one Init allowed per plugin");
  209. }
  210. }
  211. else
  212. {
  213. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  214. if (ipaPlugin != null)
  215. {
  216. ipaPlugins.Add(ipaPlugin);
  217. }
  218. }
  219. }
  220. }
  221. catch (Exception e)
  222. {
  223. Logger.log.Error($"Could not load {Path.GetFileName(file)}! {e}");
  224. }
  225. return new Tuple<IEnumerable<BSPluginMeta>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  226. }
  227. public class AppInfo
  228. {
  229. [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
  230. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  231. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  232. public static string StartupPath
  233. {
  234. get
  235. {
  236. StringBuilder stringBuilder = new StringBuilder(260);
  237. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  238. return stringBuilder.ToString();
  239. }
  240. }
  241. }
  242. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  243. }
  244. }