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.

255 lines
9.4 KiB

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