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.

584 lines
22 KiB

  1. using IPA.Loader.Features;
  2. using IPA.Logging;
  3. using IPA.Utilities;
  4. using Mono.Cecil;
  5. using Newtonsoft.Json;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Text.RegularExpressions;
  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. InitFeatures();
  27. });
  28. /// <summary>
  29. /// A class which describes a loaded plugin.
  30. /// </summary>
  31. public class PluginMetadata
  32. {
  33. /// <summary>
  34. /// The assembly the plugin was loaded from.
  35. /// </summary>
  36. public Assembly Assembly { get; internal set; }
  37. /// <summary>
  38. /// The TypeDefinition for the main type of the plugin.
  39. /// </summary>
  40. public TypeDefinition PluginType { get; internal set; }
  41. /// <summary>
  42. /// The human readable name of the plugin.
  43. /// </summary>
  44. public string Name { get; internal set; }
  45. /// <summary>
  46. /// The BeatMods ID of the plugin, or null if it doesn't have one.
  47. /// </summary>
  48. public string Id { get; internal set; }
  49. /// <summary>
  50. /// The version of the plugin.
  51. /// </summary>
  52. public Version Version { get; internal set; }
  53. /// <summary>
  54. /// The file the plugin was loaded from.
  55. /// </summary>
  56. public FileInfo File { get; internal set; }
  57. // ReSharper disable once UnusedAutoPropertyAccessor.Global
  58. /// <summary>
  59. /// The features this plugin requests.
  60. /// </summary>
  61. public IReadOnlyList<Feature> Features => InternalFeatures;
  62. internal readonly List<Feature> InternalFeatures = new List<Feature>();
  63. internal bool IsSelf;
  64. internal bool IsBare;
  65. private PluginManifest manifest;
  66. internal HashSet<PluginMetadata> Dependencies { get; } = new HashSet<PluginMetadata>();
  67. internal PluginManifest Manifest
  68. {
  69. get => manifest;
  70. set
  71. {
  72. manifest = value;
  73. Name = value.Name;
  74. Version = value.Version;
  75. Id = value.Id;
  76. }
  77. }
  78. /// <inheritdoc />
  79. public override string ToString() => $"{Name}({Id}@{Version})({PluginType?.FullName}) from '{Utils.GetRelativePath(File?.FullName, BeatSaber.InstallPath)}'";
  80. }
  81. /// <summary>
  82. /// A container object for all the data relating to a plugin.
  83. /// </summary>
  84. public class PluginInfo
  85. {
  86. internal IBeatSaberPlugin Plugin { get; set; }
  87. /// <summary>
  88. /// Metadata for the plugin.
  89. /// </summary>
  90. public PluginMetadata Metadata { get; internal set; } = new PluginMetadata();
  91. }
  92. internal static List<PluginMetadata> PluginsMetadata = new List<PluginMetadata>();
  93. private static Regex embeddedTextDescriptionPattern = new Regex(@"#!\[(.+)\]", RegexOptions.Compiled | RegexOptions.Singleline);
  94. internal static void LoadMetadata()
  95. {
  96. string[] plugins = Directory.GetFiles(BeatSaber.PluginsPath, "*.dll");
  97. try
  98. {
  99. var selfMeta = new PluginMetadata
  100. {
  101. Assembly = Assembly.GetExecutingAssembly(),
  102. File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe")),
  103. PluginType = null,
  104. IsSelf = true
  105. };
  106. string manifest;
  107. using (var manifestReader =
  108. new StreamReader(
  109. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  110. throw new InvalidOperationException()))
  111. manifest = manifestReader.ReadToEnd();
  112. selfMeta.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  113. PluginsMetadata.Add(selfMeta);
  114. }
  115. catch (Exception e)
  116. {
  117. Logger.loader.Critical("Error loading own manifest");
  118. Logger.loader.Critical(e);
  119. }
  120. foreach (var plugin in plugins)
  121. {
  122. try
  123. {
  124. var metadata = new PluginMetadata
  125. {
  126. File = new FileInfo(Path.Combine(BeatSaber.PluginsPath, plugin)),
  127. IsSelf = false
  128. };
  129. var pluginModule = AssemblyDefinition.ReadAssembly(plugin, new ReaderParameters
  130. {
  131. ReadingMode = ReadingMode.Immediate,
  132. ReadWrite = false,
  133. AssemblyResolver = new CecilLibLoader()
  134. }).MainModule;
  135. var iBeatSaberPlugin = pluginModule.ImportReference(typeof(IBeatSaberPlugin));
  136. foreach (var type in pluginModule.Types)
  137. {
  138. foreach (var inter in type.Interfaces)
  139. {
  140. var ifType = inter.InterfaceType;
  141. if (iBeatSaberPlugin.FullName == ifType.FullName)
  142. {
  143. metadata.PluginType = type;
  144. break;
  145. }
  146. }
  147. if (metadata.PluginType != null) break;
  148. }
  149. if (metadata.PluginType == null)
  150. {
  151. Logger.loader.Notice(
  152. #if DIRE_LOADER_WARNINGS
  153. $"Could not find plugin type for {Path.GetFileName(plugin)}"
  154. #else
  155. $"New plugin type not present in {Path.GetFileName(plugin)}; maybe an old plugin?"
  156. #endif
  157. );
  158. continue;
  159. }
  160. foreach (var resource in pluginModule.Resources)
  161. {
  162. if (!(resource is EmbeddedResource embedded) ||
  163. embedded.Name != $"{metadata.PluginType.Namespace}.manifest.json") continue;
  164. string manifest;
  165. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  166. manifest = manifestReader.ReadToEnd();
  167. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  168. break;
  169. }
  170. if (metadata.Manifest == null)
  171. {
  172. Logger.loader.Error("Could not find manifest.json in namespace " +
  173. $"{metadata.PluginType.Namespace} for {Path.GetFileName(plugin)}");
  174. continue;
  175. }
  176. Logger.loader.Debug($"Adding info for {Path.GetFileName(plugin)}");
  177. PluginsMetadata.Add(metadata);
  178. }
  179. catch (Exception e)
  180. {
  181. Logger.loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  182. Logger.loader.Error(e);
  183. }
  184. foreach (var meta in PluginsMetadata)
  185. { // process description include
  186. var lines = meta.Manifest.Description.Split('\n');
  187. var m = embeddedTextDescriptionPattern.Match(lines[0]);
  188. if (m.Success)
  189. {
  190. if (meta.IsBare)
  191. {
  192. Logger.loader.Warn($"Bare manifest cannot specify description file");
  193. meta.Manifest.Description = string.Join("\n", lines.Skip(1)); // ignore first line
  194. continue;
  195. }
  196. var name = m.Groups[1].Value;
  197. string description;
  198. if (!meta.IsSelf)
  199. {
  200. var resc = meta.PluginType.Module.Resources.Select(r => r as EmbeddedResource)
  201. .Where(r => r != null)
  202. .FirstOrDefault(r => r.Name == name);
  203. if (resc == null)
  204. {
  205. Logger.loader.Warn($"Could not find description file for plugin {meta.Name} ({name}); ignoring include");
  206. meta.Manifest.Description = string.Join("\n", lines.Skip(1)); // ignore first line
  207. continue;
  208. }
  209. using (var reader = new StreamReader(resc.GetResourceStream()))
  210. description = reader.ReadToEnd();
  211. }
  212. else
  213. {
  214. using (var descriptionReader =
  215. new StreamReader(
  216. meta.Assembly.GetManifestResourceStream(name) ??
  217. throw new InvalidOperationException()))
  218. description = descriptionReader.ReadToEnd();
  219. }
  220. meta.Manifest.Description = description;
  221. }
  222. }
  223. }
  224. IEnumerable<string> bareManifests = Directory.GetFiles(BeatSaber.PluginsPath, "*.json");
  225. bareManifests = bareManifests.Concat(Directory.GetFiles(BeatSaber.PluginsPath, "*.manifest"));
  226. foreach (var manifest in bareManifests)
  227. {
  228. try
  229. {
  230. var metadata = new PluginMetadata
  231. {
  232. File = new FileInfo(Path.Combine(BeatSaber.PluginsPath, manifest)),
  233. IsSelf = false,
  234. IsBare = true,
  235. };
  236. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(File.ReadAllText(manifest));
  237. Logger.loader.Debug($"Adding info for bare manifest {Path.GetFileName(manifest)}");
  238. PluginsMetadata.Add(metadata);
  239. }
  240. catch (Exception e)
  241. {
  242. Logger.loader.Error($"Could not load data for bare manifest {Path.GetFileName(manifest)}");
  243. Logger.loader.Error(e);
  244. }
  245. }
  246. }
  247. // keep track of these for the updater; it should still be able to update mods not loaded
  248. internal static HashSet<PluginMetadata> ignoredPlugins = new HashSet<PluginMetadata>();
  249. internal static void Resolve()
  250. { // resolves duplicates and conflicts, etc
  251. PluginsMetadata.Sort((a, b) => b.Version.CompareTo(a.Version));
  252. var ids = new HashSet<string>();
  253. var ignore = new HashSet<PluginMetadata>();
  254. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  255. foreach (var meta in PluginsMetadata)
  256. {
  257. if (meta.Id != null)
  258. {
  259. if (ids.Contains(meta.Id))
  260. {
  261. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  262. ignore.Add(meta);
  263. ignoredPlugins.Add(meta);
  264. continue; // because of sorted order, hightest order will always be the first one
  265. }
  266. bool processedLater = false;
  267. foreach (var meta2 in PluginsMetadata)
  268. {
  269. if (ignore.Contains(meta2)) continue;
  270. if (meta == meta2)
  271. {
  272. processedLater = true;
  273. continue;
  274. }
  275. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  276. var range = meta2.Manifest.Conflicts[meta.Id];
  277. if (!range.IsSatisfied(meta.Version)) continue;
  278. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Name}");
  279. if (processedLater)
  280. {
  281. Logger.loader.Warn($"Ignoring {meta2.Name}");
  282. ignore.Add(meta2);
  283. }
  284. else
  285. {
  286. Logger.loader.Warn($"Ignoring {meta.Name}");
  287. ignore.Add(meta);
  288. break;
  289. }
  290. }
  291. }
  292. if (ignore.Contains(meta))
  293. {
  294. ignoredPlugins.Add(meta);
  295. continue;
  296. }
  297. if (meta.Id != null)
  298. ids.Add(meta.Id);
  299. resolved.Add(meta);
  300. }
  301. PluginsMetadata = resolved;
  302. }
  303. internal static void ComputeLoadOrder()
  304. {
  305. #if DEBUG
  306. Logger.loader.Debug(string.Join(", ", PluginsMetadata.Select(p => p.ToString())));
  307. #endif
  308. bool InsertInto(HashSet<PluginMetadata> root, PluginMetadata meta, bool isRoot = false)
  309. { // this is slow, and hella recursive
  310. bool inserted = false;
  311. foreach (var sr in root)
  312. {
  313. inserted = inserted || InsertInto(sr.Dependencies, meta);
  314. if (meta.Id != null)
  315. if (sr.Manifest.Dependencies.ContainsKey(meta.Id) || sr.Manifest.LoadAfter.Contains(meta.Id))
  316. inserted = inserted || sr.Dependencies.Add(meta);
  317. if (sr.Id != null)
  318. if (meta.Manifest.LoadBefore.Contains(sr.Id))
  319. inserted = inserted || sr.Dependencies.Add(meta);
  320. }
  321. if (isRoot)
  322. {
  323. foreach (var sr in root)
  324. {
  325. InsertInto(meta.Dependencies, sr);
  326. if (sr.Id != null)
  327. if (meta.Manifest.Dependencies.ContainsKey(sr.Id) || meta.Manifest.LoadAfter.Contains(sr.Id))
  328. meta.Dependencies.Add(sr);
  329. if (meta.Id != null)
  330. if (sr.Manifest.LoadBefore.Contains(meta.Id))
  331. meta.Dependencies.Add(sr);
  332. }
  333. root.Add(meta);
  334. }
  335. return inserted;
  336. }
  337. var pluginTree = new HashSet<PluginMetadata>();
  338. foreach (var meta in PluginsMetadata)
  339. InsertInto(pluginTree, meta, true);
  340. void DeTree(List<PluginMetadata> into, HashSet<PluginMetadata> tree)
  341. {
  342. foreach (var st in tree)
  343. if (!into.Contains(st))
  344. {
  345. DeTree(into, st.Dependencies);
  346. into.Add(st);
  347. }
  348. }
  349. var deTreed = new List<PluginMetadata>();
  350. DeTree(deTreed, pluginTree);
  351. #if DEBUG
  352. Logger.loader.Debug(string.Join(", ", deTreed.Select(p => p.ToString())));
  353. #endif
  354. var metadata = new List<PluginMetadata>();
  355. var pluginsToLoad = new Dictionary<string, Version>();
  356. foreach (var meta in deTreed)
  357. {
  358. bool load = true;
  359. foreach (var dep in meta.Manifest.Dependencies)
  360. {
  361. #if DEBUG
  362. Logger.loader.Debug($"Looking for dependency {dep.Key} with version range {dep.Value.Intersect(new SemVer.Range("*.*.*"))}");
  363. #endif
  364. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key]))
  365. continue;
  366. load = false;
  367. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  368. }
  369. if (load)
  370. {
  371. metadata.Add(meta);
  372. if (meta.Id != null)
  373. pluginsToLoad.Add(meta.Id, meta.Version);
  374. }
  375. else
  376. ignoredPlugins.Add(meta);
  377. }
  378. PluginsMetadata = metadata;
  379. }
  380. internal static void InitFeatures()
  381. {
  382. var parsedFeatures = PluginsMetadata.Select(m =>
  383. Tuple.Create(m,
  384. m.Manifest.Features.Select(f =>
  385. Tuple.Create(f, Ref.Create<Feature.FeatureParse?>(null))
  386. ).ToList()
  387. )
  388. ).ToList();
  389. while (DefineFeature.NewFeature)
  390. {
  391. DefineFeature.NewFeature = false;
  392. foreach (var plugin in parsedFeatures)
  393. for (var i = 0; i < plugin.Item2.Count; i++)
  394. {
  395. var feature = plugin.Item2[i];
  396. var success = Feature.TryParseFeature(feature.Item1, plugin.Item1, out var featureObj,
  397. out var exception, out var valid, out var parsed, feature.Item2.Value);
  398. if (!success && !valid && featureObj == null && exception == null) // no feature of type found
  399. feature.Item2.Value = parsed;
  400. else if (success)
  401. {
  402. if (valid && featureObj.StoreOnPlugin)
  403. plugin.Item1.InternalFeatures.Add(featureObj);
  404. else if (!valid)
  405. Logger.features.Warn(
  406. $"Feature not valid on {plugin.Item1.Name}: {featureObj.InvalidMessage}");
  407. plugin.Item2.RemoveAt(i--);
  408. }
  409. else
  410. {
  411. Logger.features.Error($"Error parsing feature definition on {plugin.Item1.Name}");
  412. Logger.features.Error(exception);
  413. plugin.Item2.RemoveAt(i--);
  414. }
  415. }
  416. foreach (var plugin in PluginsMetadata)
  417. foreach (var feature in plugin.Features)
  418. feature.Evaluate();
  419. }
  420. foreach (var plugin in parsedFeatures)
  421. {
  422. if (plugin.Item2.Count <= 0) continue;
  423. Logger.features.Warn($"On plugin {plugin.Item1.Name}:");
  424. foreach (var feature in plugin.Item2)
  425. Logger.features.Warn($" Feature not found with name {feature.Item1}");
  426. }
  427. }
  428. internal static void Load(PluginMetadata meta)
  429. {
  430. if (meta.Assembly == null && meta.PluginType != null)
  431. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  432. }
  433. internal static PluginInfo InitPlugin(PluginMetadata meta)
  434. {
  435. if (meta.PluginType == null)
  436. return new PluginInfo()
  437. {
  438. Metadata = meta,
  439. Plugin = null
  440. };
  441. var info = new PluginInfo();
  442. try
  443. {
  444. Load(meta);
  445. Feature denyingFeature = null;
  446. if (!meta.Features.All(f => (denyingFeature = f).BeforeLoad(meta)))
  447. {
  448. Logger.loader.Warn(
  449. $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from loading! {denyingFeature?.InvalidMessage}");
  450. ignoredPlugins.Add(meta);
  451. return null;
  452. }
  453. var type = meta.Assembly.GetType(meta.PluginType.FullName);
  454. var instance = (IBeatSaberPlugin)Activator.CreateInstance(type);
  455. info.Metadata = meta;
  456. info.Plugin = instance;
  457. var init = type.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  458. if (init != null)
  459. {
  460. denyingFeature = null;
  461. if (!meta.Features.All(f => (denyingFeature = f).BeforeInit(info)))
  462. {
  463. Logger.loader.Warn(
  464. $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from initializing! {denyingFeature?.InvalidMessage}");
  465. ignoredPlugins.Add(meta);
  466. return null;
  467. }
  468. PluginInitInjector.Inject(init, info);
  469. }
  470. foreach (var feature in meta.Features)
  471. try
  472. {
  473. feature.AfterInit(info);
  474. }
  475. catch (Exception e)
  476. {
  477. Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}");
  478. }
  479. }
  480. catch (AmbiguousMatchException)
  481. {
  482. Logger.loader.Error($"Only one Init allowed per plugin (ambiguous match in {meta.Name})");
  483. // not adding to ignoredPlugins here because this should only happen in a development context
  484. // if someone fucks this up on release thats on them
  485. return null;
  486. }
  487. catch (Exception e)
  488. {
  489. Logger.loader.Error($"Could not init plugin {meta.Name}: {e}");
  490. ignoredPlugins.Add(meta);
  491. return null;
  492. }
  493. return info;
  494. }
  495. internal static List<PluginInfo> LoadPlugins() => PluginsMetadata.Select(InitPlugin).Where(p => p != null).ToList();
  496. }
  497. }