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.

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