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.

356 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. namespace IPA.Loader
  19. {
  20. /// <summary>
  21. /// The manager class for all plugins.
  22. /// </summary>
  23. public static class PluginManager
  24. {
  25. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  26. /// <summary>
  27. /// A container object for all the data relating to a plugin.
  28. /// </summary>
  29. public class PluginInfo
  30. {
  31. internal IBeatSaberPlugin Plugin { get; set; }
  32. internal string Filename { get; set; }
  33. /// <summary>
  34. /// The ModSaber updating info for the mod, or null.
  35. /// </summary>
  36. public ModsaberModInfo ModSaberInfo { get; internal set; }
  37. }
  38. /// <summary>
  39. /// An <see cref="IEnumerable"/> of new Beat Saber plugins
  40. /// </summary>
  41. internal static IEnumerable<IBeatSaberPlugin> BSPlugins
  42. {
  43. get
  44. {
  45. if(_bsPlugins == null)
  46. {
  47. LoadPlugins();
  48. }
  49. return (_bsPlugins ?? throw new InvalidOperationException()).Select(p => p.Plugin);
  50. }
  51. }
  52. private static List<PluginInfo> _bsPlugins;
  53. internal static IEnumerable<PluginInfo> BSMetas
  54. {
  55. get
  56. {
  57. if (_bsPlugins == null)
  58. {
  59. LoadPlugins();
  60. }
  61. return _bsPlugins;
  62. }
  63. }
  64. /// <summary>
  65. /// Gets info about the plugin with the specified name.
  66. /// </summary>
  67. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  68. /// <returns>the plugin info for the requested plugin or null</returns>
  69. public static PluginInfo GetPlugin(string name)
  70. {
  71. return BSMetas.FirstOrDefault(p => p.Plugin.Name == name);
  72. }
  73. /// <summary>
  74. /// Gets info about the plugin with the specified ModSaber name.
  75. /// </summary>
  76. /// <param name="name">the ModSaber name of the plugin to get (must be an exact match)</param>
  77. /// <returns>the plugin info for the requested plugin or null</returns>
  78. public static PluginInfo GetPluginFromModSaberName(string name)
  79. {
  80. return BSMetas.FirstOrDefault(p => p.ModSaberInfo.InternalName == name);
  81. }
  82. /// <summary>
  83. /// An <see cref="IEnumerable"/> of old IPA plugins
  84. /// </summary>
  85. [Obsolete("I mean, IPlugin shouldn't be used, so why should this? Not renaming to extend support for old plugins.")]
  86. public static IEnumerable<IPlugin> Plugins
  87. {
  88. get
  89. {
  90. if (_ipaPlugins == null)
  91. {
  92. LoadPlugins();
  93. }
  94. return _ipaPlugins;
  95. }
  96. }
  97. private static List<IPlugin> _ipaPlugins;
  98. internal static IConfigProvider SelfConfigProvider { get; set; }
  99. internal static readonly List<KeyValuePair<IConfigProvider,Ref<DateTime>>> configProviders = new List<KeyValuePair<IConfigProvider, Ref<DateTime>>>();
  100. private static void LoadPlugins()
  101. {
  102. string pluginDirectory = Path.Combine(Environment.CurrentDirectory, "Plugins");
  103. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  104. // so we need to resort to P/Invoke
  105. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  106. _bsPlugins = new List<PluginInfo>();
  107. _ipaPlugins = new List<IPlugin>();
  108. if (!Directory.Exists(pluginDirectory)) return;
  109. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  110. if (!Directory.Exists(cacheDir))
  111. {
  112. Directory.CreateDirectory(cacheDir);
  113. }
  114. else
  115. {
  116. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  117. {
  118. File.Delete(plugin);
  119. }
  120. }
  121. //Copy plugins to .cache
  122. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  123. foreach (string s in originalPlugins)
  124. {
  125. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  126. File.Copy(Path.Combine(pluginDirectory, s), pluginCopy);
  127. #region Fix assemblies for refactor
  128. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  129. foreach (var @ref in module.AssemblyReferences)
  130. { // fix assembly references
  131. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  132. {
  133. @ref.Name = "IPA.Loader";
  134. }
  135. }
  136. foreach (var @ref in module.GetTypeReferences())
  137. { // fix type references
  138. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  139. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  140. if (@ref.FullName == "IllusionPlugin.IBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  141. if (@ref.FullName == "IllusionPlugin.IEnhancedBeatSaberPlugin") @ref.Namespace = "IPA"; //@ref.Name = "";
  142. if (@ref.FullName == "IllusionPlugin.BeatSaber.ModsaberModInfo") @ref.Namespace = "IPA"; //@ref.Name = "";
  143. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  144. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  145. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  146. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  147. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  148. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  149. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  150. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  151. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  152. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  153. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  154. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  155. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  156. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  157. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  158. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  159. if (@ref.Namespace == "IllusionInjector.Updating.ModsaberML") @ref.Namespace = "IPA.Updating.ModSaber"; //@ref.Name = "";
  160. }
  161. module.Write(pluginCopy);
  162. #endregion
  163. }
  164. var selfPlugin = new PluginInfo
  165. {
  166. Filename = Path.Combine(Environment.CurrentDirectory, "IPA.exe"),
  167. Plugin = SelfPlugin.Instance
  168. };
  169. selfPlugin.ModSaberInfo = selfPlugin.Plugin.ModInfo;
  170. _bsPlugins.Add(selfPlugin);
  171. configProviders.Add(new KeyValuePair<IConfigProvider, Ref<DateTime>>(SelfConfigProvider = new JsonConfigProvider { Filename = Path.Combine("UserData", SelfPlugin.IPA_Name) }, 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, exeName);
  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, string exeName)
  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 (pluginInstance is IGenericEnhancedPlugin)
  214. {
  215. filter = ((IGenericEnhancedPlugin)pluginInstance).Filter;
  216. }
  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. }