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.

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