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.

267 lines
9.9 KiB

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