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.

357 lines
16 KiB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using IPA.Config;
  10. using IPA.Config.ConfigProviders;
  11. using IPA.Logging;
  12. using IPA.Old;
  13. using IPA.Updating;
  14. using IPA.Utilities;
  15. using Mono.Cecil;
  16. using UnityEngine;
  17. using Logger = IPA.Logging.Logger;
  18. namespace IPA.Loader
  19. {
  20. /// <summary>
  21. /// The manager class for all plugins.
  22. /// </summary>
  23. public static class PluginManager
  24. {
  25. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  26. /// <summary>
  27. /// A container object for all the data relating to a plugin.
  28. /// </summary>
  29. public class PluginInfo
  30. {
  31. internal IBeatSaberPlugin Plugin { get; set; }
  32. internal string Filename { get; set; }
  33. /// <summary>
  34. /// The ModSaber updating info for the mod, or null.
  35. /// </summary>
  36. public ModsaberModInfo ModSaberInfo { get; internal set; }
  37. }
  38. /// <summary>
  39. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  40. /// </summary>
  41. internal static IEnumerable<IBeatSaberPlugin> BSPlugins
  42. {
  43. get
  44. {
  45. if(_bsPlugins == null)
  46. {
  47. LoadPlugins();
  48. }
  49. return (_bsPlugins ?? throw new InvalidOperationException()).Select(p => p.Plugin);
  50. }
  51. }
  52. private static List<PluginInfo> _bsPlugins;
  53. internal static IEnumerable<PluginInfo> BSMetas
  54. {
  55. get
  56. {
  57. if (_bsPlugins == null)
  58. {
  59. LoadPlugins();
  60. }
  61. return _bsPlugins;
  62. }
  63. }
  64. /// <summary>
  65. /// Gets info about the plugin with the specified name.
  66. /// </summary>
  67. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  68. /// <returns>the plugin info for the requested plugin or null</returns>
  69. public static PluginInfo GetPlugin(string name)
  70. {
  71. return BSMetas.FirstOrDefault(p => p.Plugin.Name == name);
  72. }
  73. /// <summary>
  74. /// Gets info about the plugin with the specified ModSaber name.
  75. /// </summary>
  76. /// <param name="name">the ModSaber name of the plugin to get (must be an exact match)</param>
  77. /// <returns>the plugin info for the requested plugin or null</returns>
  78. public static PluginInfo GetPluginFromModSaberName(string name)
  79. {
  80. return BSMetas.FirstOrDefault(p => p.ModSaberInfo.InternalName == name);
  81. }
  82. /// <summary>
  83. /// An <see cref="IEnumerable"/> of old IPA plugins
  84. /// </summary>
  85. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  86. public static IEnumerable<IPlugin> Plugins
  87. {
  88. get
  89. {
  90. if (_ipaPlugins == null)
  91. {
  92. LoadPlugins();
  93. }
  94. return _ipaPlugins;
  95. }
  96. }
  97. private static List<IPlugin> _ipaPlugins;
  98. internal static IConfigProvider SelfConfigProvider { get; set; }
  99. internal static readonly List<KeyValuePair<IConfigProvider,Ref<DateTime>>> configProviders = new List<KeyValuePair<IConfigProvider, Ref<DateTime>>>();
  100. private static void LoadPlugins()
  101. {
  102. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  103. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  104. // so we need to resort to P/Invoke
  105. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  106. _bsPlugins = new List<PluginInfo>();
  107. _ipaPlugins = new List<IPlugin>();
  108. if (!Directory.Exists(pluginDirectory)) return;
  109. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  110. if (!Directory.Exists(cacheDir))
  111. {
  112. Directory.CreateDirectory(cacheDir);
  113. }
  114. else
  115. {
  116. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  117. {
  118. File.Delete(plugin);
  119. }
  120. }
  121. //Copy plugins to .cache
  122. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  123. foreach (string s in originalPlugins)
  124. {
  125. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  126. #region Fix assemblies for refactor
  127. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  128. foreach (var @ref in module.AssemblyReferences)
  129. { // fix assembly references
  130. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  131. {
  132. @ref.Name = "IPA.Loader";
  133. }
  134. }
  135. foreach (var @ref in module.GetTypeReferences())
  136. { // fix type references
  137. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  138. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  139. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  140. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  141. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  142. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  143. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  144. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  145. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  146. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  147. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  148. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  149. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  150. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  151. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  152. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  153. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  154. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  155. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  156. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  157. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  158. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  159. }
  160. module.Write(pluginCopy);
  161. #endregion
  162. }
  163. var selfPlugin = new PluginInfo
  164. {
  165. Filename = Path.Combine(BeatSaber.InstallPath, "IPA.exe"),
  166. Plugin = SelfPlugin.Instance
  167. };
  168. selfPlugin.ModSaberInfo = selfPlugin.Plugin.ModInfo;
  169. _bsPlugins.Add(selfPlugin);
  170. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(
  171. SelfConfigProvider = new JsonConfigProvider {Filename = Path.Combine("UserData", SelfPlugin.IPA_Name)},
  172. new Ref<DateTime>(SelfConfigProvider.LastModified)));
  173. SelfConfigProvider.Load();
  174. //Load copied plugins
  175. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  176. foreach (string s in copiedPlugins)
  177. {
  178. var result = LoadPluginsFromFile(s, exeName);
  179. _bsPlugins.AddRange(result.Item1);
  180. _ipaPlugins.AddRange(result.Item2);
  181. }
  182. Logger.log.Info(exeName);
  183. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  184. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  185. Logger.log.Info("-----------------------------");
  186. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  187. Logger.log.Info("-----------------------------");
  188. foreach (var plugin in _bsPlugins)
  189. {
  190. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  191. }
  192. Logger.log.Info("-----------------------------");
  193. foreach (var plugin in _ipaPlugins)
  194. {
  195. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  196. }
  197. Logger.log.Info("-----------------------------");
  198. }
  199. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file, string exeName)
  200. {
  201. List<PluginInfo> bsPlugins = new List<PluginInfo>();
  202. List<IPlugin> ipaPlugins = new List<IPlugin>();
  203. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  204. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  205. T OptionalGetPlugin<T>(Type t) where T : class
  206. {
  207. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  208. if (t.GetInterface(typeof(T).Name) != null)
  209. {
  210. try
  211. {
  212. T pluginInstance = Activator.CreateInstance(t) as T;
  213. string[] filter = null;
  214. if (typeof(T) == typeof(IPlugin) && pluginInstance is IEnhancedPlugin enhancedPlugin)
  215. filter = enhancedPlugin.Filter;
  216. else if (pluginInstance is IGenericEnhancedPlugin plugin)
  217. filter = plugin.Filter;
  218. if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  219. return pluginInstance;
  220. }
  221. catch (Exception e)
  222. {
  223. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  224. }
  225. }
  226. return null;
  227. }
  228. try
  229. {
  230. Assembly assembly = Assembly.LoadFrom(file);
  231. foreach (Type t in assembly.GetTypes())
  232. {
  233. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  234. if (bsPlugin != null)
  235. {
  236. try
  237. {
  238. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  239. if (init != null)
  240. {
  241. var initArgs = new List<object>();
  242. var initParams = init.GetParameters();
  243. Logger modLogger = null;
  244. IModPrefs modPrefs = null;
  245. IConfigProvider cfgProvider = null;
  246. foreach (var param in initParams)
  247. {
  248. var ptype = param.ParameterType;
  249. if (ptype.IsAssignableFrom(typeof(Logger))) {
  250. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  251. initArgs.Add(modLogger);
  252. }
  253. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  254. {
  255. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  256. initArgs.Add(modPrefs);
  257. }
  258. else if (ptype.IsAssignableFrom(typeof(IConfigProvider)))
  259. {
  260. if (cfgProvider == null)
  261. {
  262. cfgProvider = new JsonConfigProvider { Filename = Path.Combine("UserData", $"{bsPlugin.Name}") };
  263. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(cfgProvider, new Ref<DateTime>(cfgProvider.LastModified)));
  264. cfgProvider.Load();
  265. }
  266. initArgs.Add(cfgProvider);
  267. }
  268. else
  269. initArgs.Add(ptype.GetDefault());
  270. }
  271. init.Invoke(bsPlugin, initArgs.ToArray());
  272. }
  273. bsPlugins.Add(new PluginInfo
  274. {
  275. Plugin = bsPlugin,
  276. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  277. ModSaberInfo = bsPlugin.ModInfo
  278. });
  279. }
  280. catch (AmbiguousMatchException)
  281. {
  282. Logger.loader.Error("Only one Init allowed per plugin");
  283. }
  284. }
  285. else
  286. {
  287. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  288. if (ipaPlugin != null)
  289. {
  290. ipaPlugins.Add(ipaPlugin);
  291. }
  292. }
  293. }
  294. }
  295. catch (Exception e)
  296. {
  297. Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}");
  298. }
  299. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  300. }
  301. internal class AppInfo
  302. {
  303. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  304. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  305. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  306. public static string StartupPath
  307. {
  308. get
  309. {
  310. StringBuilder stringBuilder = new StringBuilder(260);
  311. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  312. return stringBuilder.ToString();
  313. }
  314. }
  315. }
  316. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  317. }
  318. }