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.

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