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.

355 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>>(SelfConfigProvider = new JsonConfigProvider { Filename = Path.Combine("UserData", SelfPlugin.IPA_Name) }, new Ref<DateTime>(SelfConfigProvider.LastModified)));
  171. SelfConfigProvider.Load();
  172. //Load copied plugins
  173. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  174. foreach (string s in copiedPlugins)
  175. {
  176. var result = LoadPluginsFromFile(s, exeName);
  177. _bsPlugins.AddRange(result.Item1);
  178. _ipaPlugins.AddRange(result.Item2);
  179. }
  180. Logger.log.Info(exeName);
  181. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  182. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  183. Logger.log.Info("-----------------------------");
  184. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  185. Logger.log.Info("-----------------------------");
  186. foreach (var plugin in _bsPlugins)
  187. {
  188. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  189. }
  190. Logger.log.Info("-----------------------------");
  191. foreach (var plugin in _ipaPlugins)
  192. {
  193. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  194. }
  195. Logger.log.Info("-----------------------------");
  196. }
  197. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file, string exeName)
  198. {
  199. List<PluginInfo> bsPlugins = new List<PluginInfo>();
  200. List<IPlugin> ipaPlugins = new List<IPlugin>();
  201. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  202. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  203. T OptionalGetPlugin<T>(Type t) where T : class
  204. {
  205. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  206. if (t.GetInterface(typeof(T).Name) != null)
  207. {
  208. try
  209. {
  210. T pluginInstance = Activator.CreateInstance(t) as T;
  211. string[] filter = null;
  212. if (typeof(T) == typeof(IPlugin) && pluginInstance is IEnhancedPlugin enhancedPlugin)
  213. filter = enhancedPlugin.Filter;
  214. else if (pluginInstance is IGenericEnhancedPlugin plugin)
  215. filter = plugin.Filter;
  216. if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  217. return pluginInstance;
  218. }
  219. catch (Exception e)
  220. {
  221. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  222. }
  223. }
  224. return null;
  225. }
  226. try
  227. {
  228. Assembly assembly = Assembly.LoadFrom(file);
  229. foreach (Type t in assembly.GetTypes())
  230. {
  231. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  232. if (bsPlugin != null)
  233. {
  234. try
  235. {
  236. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  237. if (init != null)
  238. {
  239. var initArgs = new List<object>();
  240. var initParams = init.GetParameters();
  241. Logger modLogger = null;
  242. IModPrefs modPrefs = null;
  243. IConfigProvider cfgProvider = null;
  244. foreach (var param in initParams)
  245. {
  246. var ptype = param.ParameterType;
  247. if (ptype.IsAssignableFrom(typeof(Logger))) {
  248. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  249. initArgs.Add(modLogger);
  250. }
  251. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  252. {
  253. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  254. initArgs.Add(modPrefs);
  255. }
  256. else if (ptype.IsAssignableFrom(typeof(IConfigProvider)))
  257. {
  258. if (cfgProvider == null)
  259. {
  260. cfgProvider = new JsonConfigProvider { Filename = Path.Combine("UserData", $"{bsPlugin.Name}") };
  261. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(cfgProvider, new Ref<DateTime>(cfgProvider.LastModified)));
  262. cfgProvider.Load();
  263. }
  264. initArgs.Add(cfgProvider);
  265. }
  266. else
  267. initArgs.Add(ptype.GetDefault());
  268. }
  269. init.Invoke(bsPlugin, initArgs.ToArray());
  270. }
  271. bsPlugins.Add(new PluginInfo
  272. {
  273. Plugin = bsPlugin,
  274. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  275. ModSaberInfo = bsPlugin.ModInfo
  276. });
  277. }
  278. catch (AmbiguousMatchException)
  279. {
  280. Logger.loader.Error("Only one Init allowed per plugin");
  281. }
  282. }
  283. else
  284. {
  285. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  286. if (ipaPlugin != null)
  287. {
  288. ipaPlugins.Add(ipaPlugin);
  289. }
  290. }
  291. }
  292. }
  293. catch (Exception e)
  294. {
  295. Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}");
  296. }
  297. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  298. }
  299. internal class AppInfo
  300. {
  301. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  302. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  303. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  304. public static string StartupPath
  305. {
  306. get
  307. {
  308. StringBuilder stringBuilder = new StringBuilder(260);
  309. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  310. return stringBuilder.ToString();
  311. }
  312. }
  313. }
  314. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  315. }
  316. }