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.

391 lines
17 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.
  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. DisabledConfig.Ref.Value.DisabledModIds.Add(plugin.Metadata.Id ?? plugin.Metadata.Name);
  78. DisabledConfig.Provider.Store(DisabledConfig.Ref.Value);
  79. if (plugin.Plugin is IDisablablePlugin disable)
  80. {
  81. try
  82. {
  83. disable.OnDisable();
  84. }
  85. catch (Exception e)
  86. {
  87. Logger.loader.Error($"Error occurred trying to disable {plugin.Metadata.Name}");
  88. Logger.loader.Error(e);
  89. }
  90. runtimeDisabled.Add(plugin);
  91. _bsPlugins.Remove(plugin);
  92. return false;
  93. }
  94. return true;
  95. }
  96. /// <summary>
  97. /// Disables a plugin.
  98. /// </summary>
  99. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to disable</param>
  100. /// <returns>whether a restart is needed to activate</returns>
  101. public static bool DisablePlugin(string pluginId) => DisablePlugin(GetPluginFromId(pluginId) ?? GetPlugin(pluginId));
  102. /// <summary>
  103. /// Enables a plugin that had been previously disabled.
  104. /// </summary>
  105. /// <param name="plugin">the plugin to enable</param>
  106. /// <returns>whether a restart is needed to activate</returns>
  107. public static bool EnablePlugin(PluginMetadata plugin)
  108. {
  109. if (plugin == null) return false;
  110. DisabledConfig.Ref.Value.DisabledModIds.Remove(plugin.Id ?? plugin.Name);
  111. DisabledConfig.Provider.Store(DisabledConfig.Ref.Value);
  112. var needsRestart = true;
  113. var runtimeInfo = runtimeDisabled.FirstOrDefault(p => p.Metadata == plugin);
  114. if (runtimeInfo != null && runtimeInfo.Plugin is IDisablablePlugin disable)
  115. {
  116. runtimeDisabled.Remove(runtimeInfo);
  117. try
  118. {
  119. disable.OnEnable();
  120. }
  121. catch (Exception e)
  122. {
  123. Logger.loader.Error($"Error occurred trying to enable {plugin.Name}");
  124. Logger.loader.Error(e);
  125. }
  126. needsRestart = false;
  127. }
  128. else
  129. {
  130. PluginLoader.DisabledPlugins.Remove(plugin);
  131. runtimeInfo = InitPlugin(plugin);
  132. }
  133. _bsPlugins.Add(runtimeInfo);
  134. return needsRestart;
  135. }
  136. /// <summary>
  137. /// Enables a plugin that had been previously disabled.
  138. /// </summary>
  139. /// <param name="pluginId">the ID, or name if the ID is null, of the plugin to enable</param>
  140. /// <returns>whether a restart is needed to activate</returns>
  141. public static bool EnablePlugin(string pluginId) =>
  142. EnablePlugin(GetDisabledPluginFromId(pluginId) ?? GetDisabledPlugin(pluginId));
  143. private static readonly List<PluginInfo> runtimeDisabled = new List<PluginInfo>();
  144. /// <summary>
  145. /// Gets a list of disabled BSIPA plugins.
  146. /// </summary>
  147. public static IEnumerable<PluginMetadata> DisabledPlugins => PluginLoader.DisabledPlugins.Concat(runtimeDisabled.Select(p => p.Metadata));
  148. /// <summary>
  149. /// Gets a list of all BSIPA plugins.
  150. /// </summary>
  151. public static IEnumerable<PluginInfo> AllPlugins => BSMetas;
  152. /// <summary>
  153. /// An <see cref="IEnumerable"/> of old IPA plugins.
  154. /// </summary>
  155. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  156. public static IEnumerable<IPlugin> Plugins => _ipaPlugins;
  157. private static List<IPlugin> _ipaPlugins;
  158. internal static IConfigProvider SelfConfigProvider { get; set; }
  159. internal static void Load()
  160. {
  161. string pluginDir = BeatSaber.PluginsPath;
  162. var gameVer = BeatSaber.GameVersion;
  163. var lastVerS = SelfConfig.SelfConfigRef.Value.LastGameVersion;
  164. var lastVer = lastVerS != null ? new SemVer.Version(lastVerS) : null;
  165. if (lastVer != null && gameVer != lastVer)
  166. {
  167. var oldPluginsName = Path.Combine(BeatSaber.InstallPath, $"{lastVer} Plugins");
  168. var newPluginsName = Path.Combine(BeatSaber.InstallPath, $"{gameVer} Plugins");
  169. ReleaseAll();
  170. if (Directory.Exists(oldPluginsName))
  171. Directory.Delete(oldPluginsName, true);
  172. Directory.Move(pluginDir, oldPluginsName);
  173. if (Directory.Exists(newPluginsName))
  174. Directory.Move(newPluginsName, pluginDir);
  175. else
  176. Directory.CreateDirectory(pluginDir);
  177. LoadTask().Wait();
  178. }
  179. SelfConfig.SelfConfigRef.Value.LastGameVersion = gameVer.ToString();
  180. SelfConfig.LoaderConfig.Store(SelfConfig.SelfConfigRef.Value);
  181. LoadPlugins();
  182. }
  183. private static void LoadPlugins()
  184. {
  185. string pluginDirectory = BeatSaber.PluginsPath;
  186. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  187. // so we need to resort to P/Invoke
  188. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  189. _bsPlugins = new List<PluginInfo>();
  190. _ipaPlugins = new List<IPlugin>();
  191. if (!Directory.Exists(pluginDirectory)) return;
  192. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  193. if (!Directory.Exists(cacheDir))
  194. {
  195. Directory.CreateDirectory(cacheDir);
  196. }
  197. else
  198. {
  199. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  200. {
  201. File.Delete(plugin);
  202. }
  203. }
  204. // initialize BSIPA plugins first
  205. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  206. //Copy plugins to .cache
  207. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  208. foreach (string s in originalPlugins)
  209. {
  210. if (PluginsMetadata.Select(m => m.File.FullName).Contains(s)) continue;
  211. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  212. #region Fix assemblies for refactor
  213. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  214. foreach (var @ref in module.AssemblyReferences)
  215. { // fix assembly references
  216. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  217. {
  218. @ref.Name = "IPA.Loader";
  219. }
  220. }
  221. foreach (var @ref in module.GetTypeReferences())
  222. { // fix type references
  223. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  224. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  225. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  226. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  227. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  228. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  229. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  230. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  231. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  232. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  233. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  234. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  235. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  236. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  237. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  238. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  239. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  240. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  241. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  242. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  243. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  244. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  245. }
  246. module.Write(pluginCopy);
  247. #endregion
  248. }
  249. //Load copied plugins
  250. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  251. foreach (string s in copiedPlugins)
  252. {
  253. var result = LoadPluginsFromFile(s);
  254. _ipaPlugins.AddRange(result.Item2);
  255. }
  256. Logger.log.Info(exeName);
  257. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  258. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  259. Logger.log.Info("-----------------------------");
  260. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  261. Logger.log.Info("-----------------------------");
  262. foreach (var plugin in _bsPlugins)
  263. {
  264. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  265. }
  266. Logger.log.Info("-----------------------------");
  267. foreach (var plugin in _ipaPlugins)
  268. {
  269. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  270. }
  271. Logger.log.Info("-----------------------------");
  272. }
  273. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file)
  274. {
  275. List<IPlugin> ipaPlugins = new List<IPlugin>();
  276. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  277. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  278. T OptionalGetPlugin<T>(Type t) where T : class
  279. {
  280. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  281. if (t.GetInterface(typeof(T).Name) != null)
  282. {
  283. try
  284. {
  285. T pluginInstance = Activator.CreateInstance(t) as T;
  286. return pluginInstance;
  287. }
  288. catch (Exception e)
  289. {
  290. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  291. }
  292. }
  293. return null;
  294. }
  295. try
  296. {
  297. Assembly assembly = Assembly.LoadFrom(file);
  298. foreach (Type t in assembly.GetTypes())
  299. {
  300. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  301. if (ipaPlugin != null)
  302. {
  303. ipaPlugins.Add(ipaPlugin);
  304. }
  305. }
  306. }
  307. catch (ReflectionTypeLoadException e)
  308. {
  309. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  310. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message) ?? new string[0])}");
  311. }
  312. catch (Exception e)
  313. {
  314. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  315. Logger.loader.Error(e);
  316. }
  317. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(null, ipaPlugins);
  318. }
  319. internal static class AppInfo
  320. {
  321. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  322. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  323. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  324. public static string StartupPath
  325. {
  326. get
  327. {
  328. StringBuilder stringBuilder = new StringBuilder(260);
  329. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  330. return stringBuilder.ToString();
  331. }
  332. }
  333. }
  334. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  335. }
  336. }