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.

464 lines
20 KiB

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