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.

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