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.

380 lines
14 KiB

  1. using IPA.Config;
  2. using IPA.Loader.Features;
  3. using IPA.Logging;
  4. using IPA.Utilities;
  5. using Mono.Cecil;
  6. using Newtonsoft.Json;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Threading.Tasks;
  13. using Version = SemVer.Version;
  14. namespace IPA.Loader
  15. {
  16. /// <summary>
  17. /// A type to manage the loading of plugins.
  18. /// </summary>
  19. public class PluginLoader
  20. {
  21. internal static Task LoadTask() => Task.Run(() =>
  22. {
  23. LoadMetadata();
  24. Resolve();
  25. ComputeLoadOrder();
  26. });
  27. /// <summary>
  28. /// A class which describes
  29. /// </summary>
  30. public class PluginMetadata
  31. {
  32. /// <summary>
  33. /// The assembly the plugin was loaded from.
  34. /// </summary>
  35. public Assembly Assembly { get; internal set; }
  36. /// <summary>
  37. /// The TypeDefinition for the main type of the plugin.
  38. /// </summary>
  39. public TypeDefinition PluginType { get; internal set; }
  40. /// <summary>
  41. /// The human readable name of the plugin.
  42. /// </summary>
  43. public string Name { get; internal set; }
  44. /// <summary>
  45. /// The ModSaber ID of the plugin, or null if it doesn't have one.
  46. /// </summary>
  47. public string Id { get; internal set; }
  48. /// <summary>
  49. /// The version of the plugin.
  50. /// </summary>
  51. public Version Version { get; internal set; }
  52. /// <summary>
  53. /// The file the plugin was loaded from.
  54. /// </summary>
  55. public FileInfo File { get; internal set; }
  56. // ReSharper disable once UnusedAutoPropertyAccessor.Global
  57. /// <summary>
  58. /// The features this plugin requests.
  59. /// </summary>
  60. public IReadOnlyList<Feature> Features => InternalFeatures;
  61. internal List<Feature> InternalFeatures = new List<Feature>();
  62. private PluginManifest manifest;
  63. internal PluginManifest Manifest
  64. {
  65. get => manifest;
  66. set
  67. {
  68. manifest = value;
  69. Name = value.Name;
  70. Version = value.Version;
  71. Id = value.Id;
  72. }
  73. }
  74. /// <inheritdoc />
  75. public override string ToString() => $"{Name}({Id}@{Version})({PluginType?.FullName}) from '{LoneFunctions.GetRelativePath(File?.FullName, BeatSaber.InstallPath)}'";
  76. }
  77. /// <summary>
  78. /// A container object for all the data relating to a plugin.
  79. /// </summary>
  80. public class PluginInfo
  81. {
  82. internal IBeatSaberPlugin Plugin { get; set; }
  83. /// <summary>
  84. /// Metadata for the plugin.
  85. /// </summary>
  86. public PluginMetadata Metadata { get; internal set; } = new PluginMetadata();
  87. }
  88. internal static List<PluginMetadata> PluginsMetadata = new List<PluginMetadata>();
  89. internal static void LoadMetadata()
  90. {
  91. string[] plugins = Directory.GetFiles(BeatSaber.PluginsPath, "*.dll");
  92. try
  93. {
  94. var selfMeta = new PluginMetadata
  95. {
  96. Assembly = Assembly.GetExecutingAssembly(),
  97. File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe")),
  98. PluginType = null
  99. };
  100. string manifest;
  101. using (var manifestReader =
  102. new StreamReader(
  103. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  104. throw new InvalidOperationException()))
  105. manifest = manifestReader.ReadToEnd();
  106. selfMeta.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  107. PluginsMetadata.Add(selfMeta);
  108. }
  109. catch (Exception e)
  110. {
  111. Logger.loader.Critical("Error loading own manifest");
  112. Logger.loader.Critical(e);
  113. }
  114. foreach (var plugin in plugins)
  115. {
  116. try
  117. {
  118. var metadata = new PluginMetadata
  119. {
  120. File = new FileInfo(Path.Combine(BeatSaber.PluginsPath, plugin))
  121. };
  122. var pluginModule = AssemblyDefinition.ReadAssembly(plugin, new ReaderParameters
  123. {
  124. ReadingMode = ReadingMode.Immediate,
  125. ReadWrite = false
  126. }).MainModule;
  127. var iBeatSaberPlugin = pluginModule.ImportReference(typeof(IBeatSaberPlugin));
  128. foreach (var type in pluginModule.Types)
  129. {
  130. foreach (var inter in type.Interfaces)
  131. {
  132. var ifType = inter.InterfaceType;
  133. if (iBeatSaberPlugin.FullName == ifType.FullName)
  134. {
  135. metadata.PluginType = type;
  136. break;
  137. }
  138. }
  139. if (metadata.PluginType != null) break;
  140. }
  141. if (metadata.PluginType == null)
  142. {
  143. Logger.loader.Warn($"Could not find plugin type for {Path.GetFileName(plugin)}");
  144. continue;
  145. }
  146. foreach (var resource in pluginModule.Resources)
  147. {
  148. if (!(resource is EmbeddedResource embedded) ||
  149. embedded.Name != $"{metadata.PluginType.Namespace}.manifest.json") continue;
  150. string manifest;
  151. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  152. manifest = manifestReader.ReadToEnd();
  153. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  154. break;
  155. }
  156. PluginsMetadata.Add(metadata);
  157. }
  158. catch (Exception e)
  159. {
  160. Logger.loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  161. Logger.loader.Error(e);
  162. }
  163. }
  164. }
  165. internal static void Resolve()
  166. { // resolves duplicates and conflicts, etc
  167. PluginsMetadata.Sort((a, b) => a.Version.CompareTo(b.Version));
  168. var ids = new HashSet<string>();
  169. var ignore = new HashSet<PluginMetadata>();
  170. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  171. foreach (var meta in PluginsMetadata)
  172. {
  173. if (meta.Id != null)
  174. {
  175. if (ids.Contains(meta.Id))
  176. {
  177. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  178. ignore.Add(meta);
  179. continue; // because of sorted order, hightest order will always be the first one
  180. }
  181. bool processedLater = false;
  182. foreach (var meta2 in PluginsMetadata)
  183. {
  184. if (ignore.Contains(meta2)) continue;
  185. if (meta == meta2)
  186. {
  187. processedLater = true;
  188. continue;
  189. }
  190. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  191. var range = meta2.Manifest.Conflicts[meta.Id];
  192. if (!range.IsSatisfied(meta.Version)) continue;
  193. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Name}");
  194. if (processedLater)
  195. {
  196. Logger.loader.Warn($"Ignoring {meta2.Name}");
  197. ignore.Add(meta2);
  198. }
  199. else
  200. {
  201. Logger.loader.Warn($"Ignoring {meta.Name}");
  202. ignore.Add(meta);
  203. break;
  204. }
  205. }
  206. }
  207. if (ignore.Contains(meta)) continue;
  208. if (meta.Id != null) ids.Add(meta.Id);
  209. resolved.Add(meta);
  210. }
  211. PluginsMetadata = resolved;
  212. }
  213. internal static void ComputeLoadOrder()
  214. {
  215. PluginsMetadata.Sort((a, b) =>
  216. {
  217. if (a.Id == b.Id) return 0;
  218. if (a.Id != null)
  219. {
  220. if (b.Manifest.Dependencies.ContainsKey(a.Id) || b.Manifest.LoadAfter.Contains(a.Id)) return -1;
  221. if (b.Manifest.LoadBefore.Contains(a.Id)) return 1;
  222. }
  223. if (b.Id != null)
  224. {
  225. if (a.Manifest.Dependencies.ContainsKey(b.Id) || a.Manifest.LoadAfter.Contains(b.Id)) return 1;
  226. if (a.Manifest.LoadBefore.Contains(b.Id)) return -1;
  227. }
  228. return 0;
  229. });
  230. var metadata = new List<PluginMetadata>();
  231. var pluginsToLoad = new Dictionary<string, Version>();
  232. foreach (var meta in PluginsMetadata)
  233. {
  234. bool load = true;
  235. foreach (var dep in meta.Manifest.Dependencies)
  236. {
  237. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key])) continue;
  238. load = false;
  239. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  240. }
  241. if (load)
  242. {
  243. metadata.Add(meta);
  244. if (meta.Id != null)
  245. pluginsToLoad.Add(meta.Id, meta.Version);
  246. }
  247. }
  248. PluginsMetadata = metadata;
  249. }
  250. internal static void Load(PluginMetadata meta)
  251. {
  252. if (meta.Assembly == null)
  253. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  254. }
  255. internal static PluginInfo InitPlugin(PluginMetadata meta)
  256. {
  257. if (meta.PluginType == null)
  258. return new PluginInfo()
  259. {
  260. Metadata = meta,
  261. Plugin = null
  262. };
  263. var info = new PluginInfo();
  264. try
  265. {
  266. Load(meta);
  267. var type = meta.Assembly.GetType(meta.PluginType.FullName);
  268. var instance = (IBeatSaberPlugin)Activator.CreateInstance(type);
  269. info.Metadata = meta;
  270. info.Plugin = instance;
  271. {
  272. var init = type.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  273. if (init != null)
  274. {
  275. var initArgs = new List<object>();
  276. var initParams = init.GetParameters();
  277. Logger modLogger = null;
  278. IModPrefs modPrefs = null;
  279. IConfigProvider cfgProvider = null;
  280. foreach (var param in initParams)
  281. {
  282. var paramType = param.ParameterType;
  283. if (paramType.IsAssignableFrom(typeof(Logger)))
  284. {
  285. if (modLogger == null) modLogger = new StandardLogger(meta.Name);
  286. initArgs.Add(modLogger);
  287. }
  288. else if (paramType.IsAssignableFrom(typeof(IModPrefs)))
  289. {
  290. if (modPrefs == null) modPrefs = new ModPrefs(instance);
  291. initArgs.Add(modPrefs);
  292. }
  293. else if (paramType.IsAssignableFrom(typeof(IConfigProvider)))
  294. {
  295. if (cfgProvider == null)
  296. {
  297. cfgProvider = Config.Config.GetProviderFor(Path.Combine("UserData", $"{meta.Name}"), param);
  298. cfgProvider.Load();
  299. }
  300. initArgs.Add(cfgProvider);
  301. }
  302. else
  303. initArgs.Add(paramType.GetDefault());
  304. }
  305. init.Invoke(instance, initArgs.ToArray());
  306. }
  307. }
  308. }
  309. catch (AmbiguousMatchException)
  310. {
  311. Logger.loader.Error($"Only one Init allowed per plugin (ambiguous match in {meta.Name})");
  312. return null;
  313. }
  314. catch (Exception e)
  315. {
  316. Logger.loader.Error($"Could not init plugin {meta.Name}: {e}");
  317. return null;
  318. }
  319. return info;
  320. }
  321. internal static List<PluginInfo> LoadPlugins() => PluginsMetadata.Select(InitPlugin).Where(p => p != null).ToList();
  322. }
  323. }