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.

313 lines
14 KiB

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