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.

496 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. 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. 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. public static IEnumerable<PluginInfo> AllPlugins => BSMetas;
  228. /// <summary>
  229. /// Converts a plugin's metadata to a <see cref="PluginInfo"/>.
  230. /// </summary>
  231. /// <param name="meta">the metadata</param>
  232. /// <returns>the plugin info</returns>
  233. public static PluginInfo InfoFromMetadata(PluginMetadata meta)
  234. {
  235. if (IsDisabled(meta))
  236. return runtimeDisabled.FirstOrDefault(p => p.Metadata == meta);
  237. else
  238. return AllPlugins.FirstOrDefault(p => p.Metadata == meta);
  239. }
  240. /// <summary>
  241. /// An <see cref="IEnumerable"/> of old IPA plugins.
  242. /// </summary>
  243. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  244. public static IEnumerable<IPlugin> Plugins => _ipaPlugins;
  245. private static List<IPlugin> _ipaPlugins;
  246. internal static IConfigProvider SelfConfigProvider { get; set; }
  247. internal static void Load()
  248. {
  249. string pluginDir = BeatSaber.PluginsPath;
  250. var gameVer = BeatSaber.GameVersion;
  251. var lastVerS = SelfConfig.SelfConfigRef.Value.LastGameVersion;
  252. var lastVer = lastVerS != null ? new SemVer.Version(lastVerS) : null;
  253. if (lastVer != null && gameVer != lastVer)
  254. {
  255. var oldPluginsName = Path.Combine(BeatSaber.InstallPath, $"{lastVer} Plugins");
  256. var newPluginsName = Path.Combine(BeatSaber.InstallPath, $"{gameVer} Plugins");
  257. ReleaseAll();
  258. if (Directory.Exists(oldPluginsName))
  259. Directory.Delete(oldPluginsName, true);
  260. Directory.Move(pluginDir, oldPluginsName);
  261. if (Directory.Exists(newPluginsName))
  262. Directory.Move(newPluginsName, pluginDir);
  263. else
  264. Directory.CreateDirectory(pluginDir);
  265. LoadTask().Wait();
  266. }
  267. SelfConfig.SelfConfigRef.Value.LastGameVersion = gameVer.ToString();
  268. SelfConfig.LoaderConfig.Store(SelfConfig.SelfConfigRef.Value);
  269. LoadPlugins();
  270. }
  271. private static void LoadPlugins()
  272. {
  273. string pluginDirectory = BeatSaber.PluginsPath;
  274. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  275. // so we need to resort to P/Invoke
  276. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  277. _bsPlugins = new List<PluginInfo>();
  278. _ipaPlugins = new List<IPlugin>();
  279. if (!Directory.Exists(pluginDirectory)) return;
  280. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  281. if (!Directory.Exists(cacheDir))
  282. {
  283. Directory.CreateDirectory(cacheDir);
  284. }
  285. else
  286. {
  287. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  288. {
  289. File.Delete(plugin);
  290. }
  291. }
  292. // initialize BSIPA plugins first
  293. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  294. //Copy plugins to .cache
  295. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  296. foreach (string s in originalPlugins)
  297. {
  298. if (PluginsMetadata.Select(m => m.File.FullName).Contains(s)) continue;
  299. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  300. #region Fix assemblies for refactor
  301. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  302. foreach (var @ref in module.AssemblyReferences)
  303. { // fix assembly references
  304. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  305. {
  306. @ref.Name = "IPA.Loader";
  307. }
  308. }
  309. foreach (var @ref in module.GetTypeReferences())
  310. { // fix type references
  311. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  312. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  313. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  314. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  315. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  316. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  317. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  318. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  319. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  320. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  321. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  322. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  323. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  324. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  325. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  326. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  327. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  328. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  329. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  330. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  331. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  332. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  333. }
  334. module.Write(pluginCopy);
  335. #endregion
  336. }
  337. //Load copied plugins
  338. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  339. foreach (string s in copiedPlugins)
  340. {
  341. var result = LoadPluginsFromFile(s);
  342. _ipaPlugins.AddRange(result.Item2);
  343. }
  344. Logger.log.Info(exeName);
  345. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  346. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  347. Logger.log.Info("-----------------------------");
  348. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  349. Logger.log.Info("-----------------------------");
  350. foreach (var plugin in _bsPlugins)
  351. {
  352. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  353. }
  354. Logger.log.Info("-----------------------------");
  355. foreach (var plugin in _ipaPlugins)
  356. {
  357. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  358. }
  359. Logger.log.Info("-----------------------------");
  360. }
  361. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file)
  362. {
  363. List<IPlugin> ipaPlugins = new List<IPlugin>();
  364. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  365. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  366. T OptionalGetPlugin<T>(Type t) where T : class
  367. {
  368. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  369. if (t.GetInterface(typeof(T).Name) != null)
  370. {
  371. try
  372. {
  373. T pluginInstance = Activator.CreateInstance(t) as T;
  374. return pluginInstance;
  375. }
  376. catch (Exception e)
  377. {
  378. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  379. }
  380. }
  381. return null;
  382. }
  383. try
  384. {
  385. Assembly assembly = Assembly.LoadFrom(file);
  386. foreach (Type t in assembly.GetTypes())
  387. {
  388. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  389. if (ipaPlugin != null)
  390. {
  391. ipaPlugins.Add(ipaPlugin);
  392. }
  393. }
  394. }
  395. catch (ReflectionTypeLoadException e)
  396. {
  397. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  398. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message) ?? new string[0])}");
  399. }
  400. catch (Exception e)
  401. {
  402. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  403. Logger.loader.Error(e);
  404. }
  405. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  406. }
  407. internal static class AppInfo
  408. {
  409. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  410. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  411. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  412. public static string StartupPath
  413. {
  414. get
  415. {
  416. StringBuilder stringBuilder = new StringBuilder(260);
  417. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  418. return stringBuilder.ToString();
  419. }
  420. }
  421. }
  422. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  423. }
  424. }