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.

479 lines
21 KiB

5 years ago
  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.Old;
  11. using IPA.Utilities;
  12. using Mono.Cecil;
  13. using UnityEngine;
  14. using Logger = IPA.Logging.Logger;
  15. using static IPA.Loader.PluginLoader;
  16. using IPA.Loader.Features;
  17. #if NET3
  18. using Net3_Proxy;
  19. using Path = Net3_Proxy.Path;
  20. using File = Net3_Proxy.File;
  21. using Directory = Net3_Proxy.Directory;
  22. #endif
  23. namespace IPA.Loader
  24. {
  25. /// <summary>
  26. /// The manager class for all plugins.
  27. /// </summary>
  28. public static class PluginManager
  29. {
  30. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  31. /// <summary>
  32. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  33. /// </summary>
  34. internal static IEnumerable<IPlugin> BSPlugins => (_bsPlugins ?? throw new InvalidOperationException()).Select(p => p.Plugin);
  35. private static List<PluginInfo> _bsPlugins;
  36. internal static IEnumerable<PluginInfo> BSMetas => _bsPlugins;
  37. /// <summary>
  38. /// Gets info about the plugin with the specified name.
  39. /// </summary>
  40. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  41. /// <returns>the plugin info for the requested plugin or null</returns>
  42. public static PluginInfo GetPlugin(string name)
  43. {
  44. return BSMetas.FirstOrDefault(p => p.Metadata.Name == name);
  45. }
  46. /// <summary>
  47. /// Gets info about the plugin with the specified ModSaber name.
  48. /// </summary>
  49. /// <param name="name">the ModSaber name of the plugin to get (must be an exact match)</param>
  50. /// <returns>the plugin info for the requested plugin or null</returns>
  51. [Obsolete("Old name. Use GetPluginFromId instead.")]
  52. public static PluginInfo GetPluginFromModSaberName(string name) => GetPluginFromId(name);
  53. /// <summary>
  54. /// Gets info about the plugin with the specified ID.
  55. /// </summary>
  56. /// <param name="name">the ID name of the plugin to get (must be an exact match)</param>
  57. /// <returns>the plugin info for the requested plugin or null</returns>
  58. public static PluginInfo GetPluginFromId(string name)
  59. {
  60. return BSMetas.FirstOrDefault(p => p.Metadata.Id == name);
  61. }
  62. /// <summary>
  63. /// Gets a disabled plugin's metadata by its name.
  64. /// </summary>
  65. /// <param name="name">the name of the disabled plugin to get</param>
  66. /// <returns>the metadata for the corresponding plugin</returns>
  67. public static PluginMetadata GetDisabledPlugin(string name) =>
  68. DisabledPlugins.FirstOrDefault(p => p.Name == name);
  69. /// <summary>
  70. /// Gets a disabled plugin's metadata by its ID.
  71. /// </summary>
  72. /// <param name="name">the ID of the disabled plugin to get</param>
  73. /// <returns>the metadata for the corresponding plugin</returns>
  74. public static PluginMetadata GetDisabledPluginFromId(string name) =>
  75. DisabledPlugins.FirstOrDefault(p => p.Id == name);
  76. /// <summary>
  77. /// Disables a plugin, and all dependents.
  78. /// </summary>
  79. /// <param name="plugin">the plugin to disable</param>
  80. /// <returns>whether or not it needs a restart to enable</returns>
  81. public static bool DisablePlugin(PluginInfo plugin)
  82. {
  83. if (plugin == null) return false;
  84. if (plugin.Metadata.IsBare)
  85. {
  86. Logger.loader.Warn($"Trying to disable bare manifest");
  87. return false;
  88. }
  89. if (IsDisabled(plugin.Metadata)) return false;
  90. var needsRestart = false;
  91. Logger.loader.Info($"Disabling {plugin.Metadata.Name}");
  92. var dependents = BSMetas.Where(m => m.Metadata.Dependencies.Contains(plugin.Metadata)).ToList();
  93. needsRestart = dependents.Aggregate(needsRestart, (b, p) => DisablePlugin(p) || b);
  94. DisabledConfig.Instance.DisabledModIds.Add(plugin.Metadata.Id ?? plugin.Metadata.Name);
  95. if (!needsRestart && plugin.Plugin is IDisablablePlugin disable)
  96. {
  97. try
  98. {
  99. disable.OnDisable();
  100. }
  101. catch (Exception e)
  102. {
  103. Logger.loader.Error($"Error occurred trying to disable {plugin.Metadata.Name}");
  104. Logger.loader.Error(e);
  105. }
  106. if (needsRestart)
  107. Logger.loader.Warn($"Disablable plugin has non-disablable dependents; some things may not work properly");
  108. }
  109. else needsRestart = true;
  110. runtimeDisabled.Add(plugin);
  111. _bsPlugins.Remove(plugin);
  112. try
  113. {
  114. PluginDisabled?.Invoke(plugin.Metadata, needsRestart);
  115. }
  116. catch (Exception e)
  117. {
  118. Logger.loader.Error($"Error occurred invoking disable event for {plugin.Metadata.Name}");
  119. Logger.loader.Error(e);
  120. }
  121. return needsRestart;
  122. }
  123. /// <summary>
  124. /// Disables a plugin, and all dependents.
  125. /// </summary>
  126. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to disable</param>
  127. /// <returns>whether a restart is needed to activate</returns>
  128. public static bool DisablePlugin(string pluginId) => DisablePlugin(GetPluginFromId(pluginId) ?? GetPlugin(pluginId));
  129. /// <summary>
  130. /// Enables a plugin that had been previously disabled.
  131. /// </summary>
  132. /// <param name="plugin">the plugin to enable</param>
  133. /// <returns>whether a restart is needed to activate</returns>
  134. public static bool EnablePlugin(PluginMetadata plugin)
  135. { // TODO: fix some of this behaviour, by adding better support for runtime enable/disable of mods
  136. if (plugin == null) return false;
  137. if (plugin.IsBare)
  138. {
  139. Logger.loader.Warn($"Trying to enable bare manifest");
  140. return false;
  141. }
  142. if (!IsDisabled(plugin)) return false;
  143. Logger.loader.Info($"Enabling {plugin.Name}");
  144. DisabledConfig.Instance.DisabledModIds.Remove(plugin.Id ?? plugin.Name);
  145. var needsRestart = true;
  146. var depsNeedRestart = plugin.Dependencies.Aggregate(false, (b, p) => EnablePlugin(p) || b);
  147. var runtimeInfo = runtimeDisabled.FirstOrDefault(p => p.Metadata == plugin);
  148. if (runtimeInfo != null && runtimeInfo.Plugin is IPlugin newPlugin)
  149. {
  150. try
  151. {
  152. newPlugin.OnEnable();
  153. }
  154. catch (Exception e)
  155. {
  156. Logger.loader.Error($"Error occurred trying to enable {plugin.Name}");
  157. Logger.loader.Error(e);
  158. }
  159. needsRestart = false;
  160. }
  161. else
  162. {
  163. PluginLoader.DisabledPlugins.Remove(plugin);
  164. if (runtimeInfo == null)
  165. {
  166. runtimeInfo = InitPlugin(plugin, AllPlugins.Select(i => i.Metadata));
  167. needsRestart = false;
  168. }
  169. }
  170. if (runtimeInfo != null)
  171. runtimeDisabled.Remove(runtimeInfo);
  172. _bsPlugins.Add(runtimeInfo);
  173. try
  174. {
  175. PluginEnabled?.Invoke(runtimeInfo, needsRestart || depsNeedRestart);
  176. }
  177. catch (Exception e)
  178. {
  179. Logger.loader.Error($"Error occurred invoking enable event for {plugin.Name}");
  180. Logger.loader.Error(e);
  181. }
  182. return needsRestart || depsNeedRestart;
  183. }
  184. /// <summary>
  185. /// Enables a plugin that had been previously disabled.
  186. /// </summary>
  187. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to enable</param>
  188. /// <returns>whether a restart is needed to activate</returns>
  189. public static bool EnablePlugin(string pluginId) =>
  190. EnablePlugin(GetDisabledPluginFromId(pluginId) ?? GetDisabledPlugin(pluginId));
  191. /// <summary>
  192. /// Checks if a given plugin is disabled.
  193. /// </summary>
  194. /// <param name="meta">the plugin to check</param>
  195. /// <returns><see langword="true"/> if the plugin is disabled, <see langword="false"/> otherwise.</returns>
  196. public static bool IsDisabled(PluginMetadata meta) => DisabledPlugins.Contains(meta);
  197. /// <summary>
  198. /// Checks if a given plugin is enabled.
  199. /// </summary>
  200. /// <param name="meta">the plugin to check</param>
  201. /// <returns><see langword="true"/> if the plugin is enabled, <see langword="false"/> otherwise.</returns>
  202. public static bool IsEnabled(PluginMetadata meta) => BSMetas.Any(p => p.Metadata == meta);
  203. private static readonly List<PluginInfo> runtimeDisabled = new List<PluginInfo>();
  204. /// <summary>
  205. /// Gets a list of disabled BSIPA plugins.
  206. /// </summary>
  207. /// <value>a collection of all disabled plugins as <see cref="PluginMetadata"/></value>
  208. public static IEnumerable<PluginMetadata> DisabledPlugins => PluginLoader.DisabledPlugins.Concat(runtimeDisabled.Select(p => p.Metadata));
  209. /// <summary>
  210. /// An invoker for the <see cref="PluginEnabled"/> event.
  211. /// </summary>
  212. /// <param name="plugin">the plugin that was enabled</param>
  213. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  214. public delegate void PluginEnableDelegate(PluginInfo plugin, bool needsRestart);
  215. /// <summary>
  216. /// An invoker for the <see cref="PluginDisabled"/> event.
  217. /// </summary>
  218. /// <param name="plugin">the plugin that was disabled</param>
  219. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  220. public delegate void PluginDisableDelegate(PluginMetadata plugin, bool needsRestart);
  221. /// <summary>
  222. /// Called whenever a plugin is enabled.
  223. /// </summary>
  224. public static event PluginEnableDelegate PluginEnabled;
  225. /// <summary>
  226. /// Called whenever a plugin is disabled.
  227. /// </summary>
  228. public static event PluginDisableDelegate PluginDisabled;
  229. /// <summary>
  230. /// Gets a list of all BSIPA plugins.
  231. /// </summary>
  232. /// <value>a collection of all enabled plugins as <see cref="PluginInfo"/>s</value>
  233. public static IEnumerable<PluginInfo> AllPlugins => BSMetas;
  234. /// <summary>
  235. /// Converts a plugin's metadata to a <see cref="PluginInfo"/>.
  236. /// </summary>
  237. /// <param name="meta">the metadata</param>
  238. /// <returns>the plugin info</returns>
  239. public static PluginInfo InfoFromMetadata(PluginMetadata meta)
  240. {
  241. if (IsDisabled(meta))
  242. return runtimeDisabled.FirstOrDefault(p => p.Metadata == meta);
  243. else
  244. return AllPlugins.FirstOrDefault(p => p.Metadata == meta);
  245. }
  246. /// <summary>
  247. /// An <see cref="IEnumerable"/> of old IPA plugins.
  248. /// </summary>
  249. /// <value>all legacy plugin instances</value>
  250. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  251. public static IEnumerable<Old.IPlugin> Plugins => _ipaPlugins;
  252. private static List<Old.IPlugin> _ipaPlugins;
  253. internal static IConfigProvider SelfConfigProvider { get; set; }
  254. internal static void Load()
  255. {
  256. string pluginDirectory = BeatSaber.PluginsPath;
  257. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  258. // so we need to resort to P/Invoke
  259. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  260. _bsPlugins = new List<PluginInfo>();
  261. _ipaPlugins = new List<Old.IPlugin>();
  262. if (!Directory.Exists(pluginDirectory)) return;
  263. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  264. if (!Directory.Exists(cacheDir))
  265. {
  266. Directory.CreateDirectory(cacheDir);
  267. }
  268. else
  269. {
  270. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  271. {
  272. File.Delete(plugin);
  273. }
  274. }
  275. // initialize BSIPA plugins first
  276. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  277. NoRuntimeEnableFeature.HaveLoadedPlugins = true;
  278. var metadataPaths = PluginsMetadata.Select(m => m.File.FullName).ToList();
  279. var ignoredPaths = ignoredPlugins.Select(m => m.Key.File.FullName).ToList();
  280. var disabledPaths = DisabledPlugins.Select(m => m.File.FullName).ToList();
  281. //Copy plugins to .cache
  282. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  283. foreach (string s in originalPlugins)
  284. {
  285. if (metadataPaths.Contains(s)) continue;
  286. if (ignoredPaths.Contains(s)) continue;
  287. if (disabledPaths.Contains(s)) continue;
  288. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  289. #region Fix assemblies for refactor
  290. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  291. foreach (var @ref in module.AssemblyReferences)
  292. { // fix assembly references
  293. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  294. {
  295. @ref.Name = "IPA.Loader";
  296. }
  297. }
  298. foreach (var @ref in module.GetTypeReferences())
  299. { // fix type references
  300. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  301. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  302. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  303. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  304. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  305. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  306. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  307. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  308. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  309. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  310. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  311. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  312. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  313. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  314. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  315. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  316. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  317. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  318. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  319. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  320. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  321. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  322. }
  323. module.Write(pluginCopy);
  324. #endregion
  325. }
  326. //Load copied plugins
  327. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  328. foreach (string s in copiedPlugins)
  329. {
  330. var result = LoadPluginsFromFile(s);
  331. _ipaPlugins.AddRange(result.Item2);
  332. }
  333. Logger.log.Info(exeName);
  334. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  335. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  336. Logger.log.Info("-----------------------------");
  337. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  338. Logger.log.Info("-----------------------------");
  339. foreach (var plugin in _bsPlugins)
  340. {
  341. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  342. }
  343. Logger.log.Info("-----------------------------");
  344. foreach (var plugin in _ipaPlugins)
  345. {
  346. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  347. }
  348. Logger.log.Info("-----------------------------");
  349. }
  350. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<Old.IPlugin>> LoadPluginsFromFile(string file)
  351. {
  352. var ipaPlugins = new List<Old.IPlugin>();
  353. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  354. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<Old.IPlugin>>(null, ipaPlugins);
  355. T OptionalGetPlugin<T>(Type t) where T : class
  356. {
  357. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  358. if (t.GetInterface(typeof(T).Name) != null)
  359. {
  360. try
  361. {
  362. T pluginInstance = Activator.CreateInstance(t) as T;
  363. return pluginInstance;
  364. }
  365. catch (Exception e)
  366. {
  367. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  368. }
  369. }
  370. return null;
  371. }
  372. try
  373. {
  374. Assembly assembly = Assembly.LoadFrom(file);
  375. foreach (Type t in assembly.GetTypes())
  376. {
  377. var ipaPlugin = OptionalGetPlugin<Old.IPlugin>(t);
  378. if (ipaPlugin != null)
  379. {
  380. ipaPlugins.Add(ipaPlugin);
  381. }
  382. }
  383. }
  384. catch (ReflectionTypeLoadException e)
  385. {
  386. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  387. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message).StrJP() ?? new string[0])}");
  388. }
  389. catch (Exception e)
  390. {
  391. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  392. Logger.loader.Error(e);
  393. }
  394. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<Old.IPlugin>>(null, ipaPlugins);
  395. }
  396. internal static class AppInfo
  397. {
  398. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  399. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  400. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  401. public static string StartupPath
  402. {
  403. get
  404. {
  405. StringBuilder stringBuilder = new StringBuilder(260);
  406. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  407. return stringBuilder.ToString();
  408. }
  409. }
  410. }
  411. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  412. }
  413. }