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.

357 lines
16 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.Config.ConfigProviders;
  11. using IPA.Logging;
  12. using IPA.Old;
  13. using IPA.Updating;
  14. using IPA.Utilities;
  15. using Mono.Cecil;
  16. using UnityEngine;
  17. using Logger = IPA.Logging.Logger;
  18. using static IPA.Loader.PluginLoader;
  19. namespace IPA.Loader
  20. {
  21. /// <summary>
  22. /// The manager class for all plugins.
  23. /// </summary>
  24. public static class PluginManager
  25. {
  26. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  27. /// <summary>
  28. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  29. /// </summary>
  30. internal static IEnumerable<IBeatSaberPlugin> BSPlugins
  31. {
  32. get
  33. {
  34. if(_bsPlugins == null)
  35. {
  36. LoadPlugins();
  37. }
  38. return (_bsPlugins ?? throw new InvalidOperationException()).Select(p => p.Plugin);
  39. }
  40. }
  41. private static List<PluginInfo> _bsPlugins;
  42. internal static IEnumerable<PluginInfo> BSMetas
  43. {
  44. get
  45. {
  46. if (_bsPlugins == null)
  47. {
  48. LoadPlugins();
  49. }
  50. return _bsPlugins;
  51. }
  52. }
  53. /// <summary>
  54. /// Gets info about the plugin with the specified name.
  55. /// </summary>
  56. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  57. /// <returns>the plugin info for the requested plugin or null</returns>
  58. public static PluginInfo GetPlugin(string name)
  59. {
  60. return BSMetas.FirstOrDefault(p => p.Plugin.Name == name);
  61. }
  62. /// <summary>
  63. /// Gets info about the plugin with the specified ModSaber name.
  64. /// </summary>
  65. /// <param name="name">the ModSaber name of the plugin to get (must be an exact match)</param>
  66. /// <returns>the plugin info for the requested plugin or null</returns>
  67. public static PluginInfo GetPluginFromModSaberName(string name)
  68. {
  69. return BSMetas.FirstOrDefault(p => p.Metadata.Id == name);
  70. }
  71. /// <summary>
  72. /// An <see cref="IEnumerable"/> of old IPA plugins
  73. /// </summary>
  74. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  75. public static IEnumerable<IPlugin> Plugins
  76. {
  77. get
  78. {
  79. if (_ipaPlugins == null)
  80. {
  81. LoadPlugins();
  82. }
  83. return _ipaPlugins;
  84. }
  85. }
  86. private static List<IPlugin> _ipaPlugins;
  87. internal static IConfigProvider SelfConfigProvider { get; set; }
  88. internal static readonly List<KeyValuePair<IConfigProvider,Ref<DateTime>>> configProviders = new List<KeyValuePair<IConfigProvider, Ref<DateTime>>>();
  89. private static void LoadPlugins()
  90. {
  91. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  92. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  93. // so we need to resort to P/Invoke
  94. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  95. _bsPlugins = new List<PluginInfo>();
  96. _ipaPlugins = new List<IPlugin>();
  97. if (!Directory.Exists(pluginDirectory)) return;
  98. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  99. if (!Directory.Exists(cacheDir))
  100. {
  101. Directory.CreateDirectory(cacheDir);
  102. }
  103. else
  104. {
  105. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  106. {
  107. File.Delete(plugin);
  108. }
  109. }
  110. //Copy plugins to .cache
  111. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  112. foreach (string s in originalPlugins)
  113. {
  114. if (PluginsMetadata.Select(m => m.File.Name).Contains(s)) continue;
  115. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  116. #region Fix assemblies for refactor
  117. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  118. foreach (var @ref in module.AssemblyReferences)
  119. { // fix assembly references
  120. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  121. {
  122. @ref.Name = "IPA.Loader";
  123. }
  124. }
  125. foreach (var @ref in module.GetTypeReferences())
  126. { // fix type references
  127. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  128. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  129. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  130. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  131. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  132. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  133. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  134. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  135. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  136. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  137. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  138. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  139. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  140. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  141. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  142. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  143. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  144. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  145. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  146. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  147. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  148. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  149. }
  150. module.Write(pluginCopy);
  151. #endregion
  152. }
  153. var selfPlugin = new PluginInfo
  154. {
  155. Filename = Path.Combine(BeatSaber.InstallPath, "IPA.exe"),
  156. Plugin = SelfPlugin.Instance
  157. };
  158. selfPlugin.Metadata.Manifest = new PluginManifest
  159. {
  160. Author = "DaNike",
  161. Features = new string[0],
  162. Description = "",
  163. Version = new SemVer.Version(SelfPlugin.IPA_Version),
  164. GameVersion = BeatSaber.GameVersion,
  165. Id = "beatsaber-ipa-reloaded"
  166. };
  167. selfPlugin.Metadata.File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe"));
  168. _bsPlugins.Add(selfPlugin);
  169. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(
  170. SelfConfigProvider = new JsonConfigProvider {Filename = Path.Combine("UserData", SelfPlugin.IPA_Name)},
  171. new Ref<DateTime>(SelfConfigProvider.LastModified)));
  172. SelfConfigProvider.Load();
  173. //Load copied plugins
  174. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  175. foreach (string s in copiedPlugins)
  176. {
  177. var result = LoadPluginsFromFile(s);
  178. _bsPlugins.AddRange(result.Item1);
  179. _ipaPlugins.AddRange(result.Item2);
  180. }
  181. Logger.log.Info(exeName);
  182. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  183. Logger.log.Info($"Game version {BeatSaber.GameVersion}");
  184. Logger.log.Info("-----------------------------");
  185. Logger.log.Info($"Loading plugins from {LoneFunctions.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  186. Logger.log.Info("-----------------------------");
  187. foreach (var plugin in _bsPlugins)
  188. {
  189. Logger.log.Info($"{plugin.Plugin.Name}: {plugin.Plugin.Version}");
  190. }
  191. Logger.log.Info("-----------------------------");
  192. foreach (var plugin in _ipaPlugins)
  193. {
  194. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  195. }
  196. Logger.log.Info("-----------------------------");
  197. }
  198. private static Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>> LoadPluginsFromFile(string file)
  199. {
  200. List<PluginInfo> bsPlugins = new List<PluginInfo>();
  201. List<IPlugin> ipaPlugins = new List<IPlugin>();
  202. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  203. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  204. T OptionalGetPlugin<T>(Type t) where T : class
  205. {
  206. // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯)
  207. if (t.GetInterface(typeof(T).Name) != null)
  208. {
  209. try
  210. {
  211. T pluginInstance = Activator.CreateInstance(t) as T;
  212. /*string[] filter = null;
  213. if (typeof(T) == typeof(IPlugin) && pluginInstance is IEnhancedPlugin enhancedPlugin)
  214. filter = enhancedPlugin.Filter;
  215. else if (pluginInstance is IGenericEnhancedPlugin plugin)
  216. filter = plugin.Filter;*/
  217. //if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
  218. return pluginInstance;
  219. }
  220. catch (Exception e)
  221. {
  222. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  223. }
  224. }
  225. return null;
  226. }
  227. try
  228. {
  229. Assembly assembly = Assembly.LoadFrom(file);
  230. foreach (Type t in assembly.GetTypes())
  231. {
  232. IBeatSaberPlugin bsPlugin = OptionalGetPlugin<IBeatSaberPlugin>(t);
  233. if (bsPlugin != null)
  234. {
  235. try
  236. {
  237. var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  238. if (init != null)
  239. {
  240. var initArgs = new List<object>();
  241. var initParams = init.GetParameters();
  242. Logger modLogger = null;
  243. IModPrefs modPrefs = null;
  244. IConfigProvider cfgProvider = null;
  245. foreach (var param in initParams)
  246. {
  247. var ptype = param.ParameterType;
  248. if (ptype.IsAssignableFrom(typeof(Logger))) {
  249. if (modLogger == null) modLogger = new StandardLogger(bsPlugin.Name);
  250. initArgs.Add(modLogger);
  251. }
  252. else if (ptype.IsAssignableFrom(typeof(IModPrefs)))
  253. {
  254. if (modPrefs == null) modPrefs = new ModPrefs(bsPlugin);
  255. initArgs.Add(modPrefs);
  256. }
  257. else if (ptype.IsAssignableFrom(typeof(IConfigProvider)))
  258. {
  259. if (cfgProvider == null)
  260. {
  261. cfgProvider = new JsonConfigProvider { Filename = Path.Combine("UserData", $"{bsPlugin.Name}") };
  262. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(cfgProvider, new Ref<DateTime>(cfgProvider.LastModified)));
  263. cfgProvider.Load();
  264. }
  265. initArgs.Add(cfgProvider);
  266. }
  267. else
  268. initArgs.Add(ptype.GetDefault());
  269. }
  270. init.Invoke(bsPlugin, initArgs.ToArray());
  271. }
  272. bsPlugins.Add(new PluginInfo
  273. {
  274. Plugin = bsPlugin,
  275. Filename = file.Replace("\\.cache", ""), // quick and dirty fix
  276. //ModSaberInfo = bsPlugin.ModInfo
  277. });
  278. }
  279. catch (AmbiguousMatchException)
  280. {
  281. Logger.loader.Error("Only one Init allowed per plugin");
  282. }
  283. }
  284. else
  285. {
  286. IPlugin ipaPlugin = OptionalGetPlugin<IPlugin>(t);
  287. if (ipaPlugin != null)
  288. {
  289. ipaPlugins.Add(ipaPlugin);
  290. }
  291. }
  292. }
  293. }
  294. catch (Exception e)
  295. {
  296. Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}");
  297. }
  298. return new Tuple<IEnumerable<PluginInfo>, IEnumerable<IPlugin>>(bsPlugins, ipaPlugins);
  299. }
  300. internal class AppInfo
  301. {
  302. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  303. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  304. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  305. public static string StartupPath
  306. {
  307. get
  308. {
  309. StringBuilder stringBuilder = new StringBuilder(260);
  310. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  311. return stringBuilder.ToString();
  312. }
  313. }
  314. }
  315. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  316. }
  317. }