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.

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