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.

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