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.

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