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.

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