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.

440 lines
16 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.Threading.Tasks;
  12. using Version = SemVer.Version;
  13. namespace IPA.Loader
  14. {
  15. /// <summary>
  16. /// A type to manage the loading of plugins.
  17. /// </summary>
  18. public class PluginLoader
  19. {
  20. internal static Task LoadTask() => Task.Run(() =>
  21. {
  22. LoadMetadata();
  23. Resolve();
  24. ComputeLoadOrder();
  25. InitFeatures();
  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 readonly List<Feature> InternalFeatures = new List<Feature>();
  62. internal bool IsSelf;
  63. private PluginManifest manifest;
  64. internal PluginManifest Manifest
  65. {
  66. get => manifest;
  67. set
  68. {
  69. manifest = value;
  70. Name = value.Name;
  71. Version = value.Version;
  72. Id = value.Id;
  73. }
  74. }
  75. /// <inheritdoc />
  76. public override string ToString() => $"{Name}({Id}@{Version})({PluginType?.FullName}) from '{Utils.GetRelativePath(File?.FullName, BeatSaber.InstallPath)}'";
  77. }
  78. /// <summary>
  79. /// A container object for all the data relating to a plugin.
  80. /// </summary>
  81. public class PluginInfo
  82. {
  83. internal IBeatSaberPlugin Plugin { get; set; }
  84. /// <summary>
  85. /// Metadata for the plugin.
  86. /// </summary>
  87. public PluginMetadata Metadata { get; internal set; } = new PluginMetadata();
  88. }
  89. internal static List<PluginMetadata> PluginsMetadata = new List<PluginMetadata>();
  90. internal static void LoadMetadata()
  91. {
  92. string[] plugins = Directory.GetFiles(BeatSaber.PluginsPath, "*.dll");
  93. try
  94. {
  95. var selfMeta = new PluginMetadata
  96. {
  97. Assembly = Assembly.GetExecutingAssembly(),
  98. File = new FileInfo(Path.Combine(BeatSaber.InstallPath, "IPA.exe")),
  99. PluginType = null,
  100. IsSelf = true
  101. };
  102. string manifest;
  103. using (var manifestReader =
  104. new StreamReader(
  105. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  106. throw new InvalidOperationException()))
  107. manifest = manifestReader.ReadToEnd();
  108. selfMeta.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  109. PluginsMetadata.Add(selfMeta);
  110. }
  111. catch (Exception e)
  112. {
  113. Logger.loader.Critical("Error loading own manifest");
  114. Logger.loader.Critical(e);
  115. }
  116. foreach (var plugin in plugins)
  117. {
  118. try
  119. {
  120. var metadata = new PluginMetadata
  121. {
  122. File = new FileInfo(Path.Combine(BeatSaber.PluginsPath, plugin)),
  123. IsSelf = false
  124. };
  125. var pluginModule = AssemblyDefinition.ReadAssembly(plugin, new ReaderParameters
  126. {
  127. ReadingMode = ReadingMode.Immediate,
  128. ReadWrite = false,
  129. AssemblyResolver = new CecilLibLoader()
  130. }).MainModule;
  131. var iBeatSaberPlugin = pluginModule.ImportReference(typeof(IBeatSaberPlugin));
  132. foreach (var type in pluginModule.Types)
  133. {
  134. foreach (var inter in type.Interfaces)
  135. {
  136. var ifType = inter.InterfaceType;
  137. if (iBeatSaberPlugin.FullName == ifType.FullName)
  138. {
  139. metadata.PluginType = type;
  140. break;
  141. }
  142. }
  143. if (metadata.PluginType != null) break;
  144. }
  145. if (metadata.PluginType == null)
  146. {
  147. Logger.loader.Warn($"Could not find plugin type for {Path.GetFileName(plugin)}");
  148. continue;
  149. }
  150. foreach (var resource in pluginModule.Resources)
  151. {
  152. if (!(resource is EmbeddedResource embedded) ||
  153. embedded.Name != $"{metadata.PluginType.Namespace}.manifest.json") continue;
  154. string manifest;
  155. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  156. manifest = manifestReader.ReadToEnd();
  157. metadata.Manifest = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  158. break;
  159. }
  160. if (metadata.Manifest == null)
  161. {
  162. Logger.loader.Error("Could not find manifest.json in namespace " +
  163. $"{metadata.PluginType.Namespace} for {Path.GetFileName(plugin)}");
  164. continue;
  165. }
  166. Logger.loader.Debug($"Adding info for {Path.GetFileName(plugin)}");
  167. PluginsMetadata.Add(metadata);
  168. }
  169. catch (Exception e)
  170. {
  171. Logger.loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  172. Logger.loader.Error(e);
  173. }
  174. }
  175. }
  176. internal static void Resolve()
  177. { // resolves duplicates and conflicts, etc
  178. PluginsMetadata.Sort((a, b) => a.Version.CompareTo(b.Version));
  179. var ids = new HashSet<string>();
  180. var ignore = new HashSet<PluginMetadata>();
  181. var resolved = new List<PluginMetadata>(PluginsMetadata.Count);
  182. foreach (var meta in PluginsMetadata)
  183. {
  184. if (meta.Id != null)
  185. {
  186. if (ids.Contains(meta.Id))
  187. {
  188. Logger.loader.Warn($"Found duplicates of {meta.Id}, using newest");
  189. ignore.Add(meta);
  190. continue; // because of sorted order, hightest order will always be the first one
  191. }
  192. bool processedLater = false;
  193. foreach (var meta2 in PluginsMetadata)
  194. {
  195. if (ignore.Contains(meta2)) continue;
  196. if (meta == meta2)
  197. {
  198. processedLater = true;
  199. continue;
  200. }
  201. if (!meta2.Manifest.Conflicts.ContainsKey(meta.Id)) continue;
  202. var range = meta2.Manifest.Conflicts[meta.Id];
  203. if (!range.IsSatisfied(meta.Version)) continue;
  204. Logger.loader.Warn($"{meta.Id}@{meta.Version} conflicts with {meta2.Name}");
  205. if (processedLater)
  206. {
  207. Logger.loader.Warn($"Ignoring {meta2.Name}");
  208. ignore.Add(meta2);
  209. }
  210. else
  211. {
  212. Logger.loader.Warn($"Ignoring {meta.Name}");
  213. ignore.Add(meta);
  214. break;
  215. }
  216. }
  217. }
  218. if (ignore.Contains(meta)) continue;
  219. if (meta.Id != null) ids.Add(meta.Id);
  220. resolved.Add(meta);
  221. }
  222. PluginsMetadata = resolved;
  223. }
  224. internal static void ComputeLoadOrder()
  225. {
  226. PluginsMetadata.Sort((a, b) =>
  227. {
  228. if (a.Id == b.Id) return 0;
  229. if (a.Id != null)
  230. {
  231. if (b.Manifest.Dependencies.ContainsKey(a.Id) || b.Manifest.LoadAfter.Contains(a.Id)) return -1;
  232. if (b.Manifest.LoadBefore.Contains(a.Id)) return 1;
  233. }
  234. if (b.Id != null)
  235. {
  236. if (a.Manifest.Dependencies.ContainsKey(b.Id) || a.Manifest.LoadAfter.Contains(b.Id)) return 1;
  237. if (a.Manifest.LoadBefore.Contains(b.Id)) return -1;
  238. }
  239. return 0;
  240. });
  241. var metadata = new List<PluginMetadata>();
  242. var pluginsToLoad = new Dictionary<string, Version>();
  243. foreach (var meta in PluginsMetadata)
  244. {
  245. bool load = true;
  246. foreach (var dep in meta.Manifest.Dependencies)
  247. {
  248. if (pluginsToLoad.ContainsKey(dep.Key) && dep.Value.IsSatisfied(pluginsToLoad[dep.Key])) continue;
  249. load = false;
  250. Logger.loader.Warn($"{meta.Name} is missing dependency {dep.Key}@{dep.Value}");
  251. }
  252. if (load)
  253. {
  254. metadata.Add(meta);
  255. if (meta.Id != null)
  256. pluginsToLoad.Add(meta.Id, meta.Version);
  257. }
  258. }
  259. PluginsMetadata = metadata;
  260. }
  261. internal static void InitFeatures()
  262. {
  263. var parsedFeatures = PluginsMetadata.Select(m =>
  264. Tuple.Create(m,
  265. m.Manifest.Features.Select(f =>
  266. Tuple.Create(f, Ref.Create<Feature.FeatureParse?>(null))
  267. ).ToList()
  268. )
  269. ).ToList();
  270. while (DefineFeature.NewFeature)
  271. {
  272. DefineFeature.NewFeature = false;
  273. foreach (var plugin in parsedFeatures)
  274. for (var i = 0; i < plugin.Item2.Count; i++)
  275. {
  276. var feature = plugin.Item2[i];
  277. var success = Feature.TryParseFeature(feature.Item1, plugin.Item1, out var featureObj,
  278. out var exception, out var valid, out var parsed, feature.Item2.Value);
  279. if (!success && !valid && featureObj == null && exception == null) // no feature of type found
  280. feature.Item2.Value = parsed;
  281. else if (success)
  282. {
  283. if (valid && featureObj.StoreOnPlugin)
  284. plugin.Item1.InternalFeatures.Add(featureObj);
  285. else if (!valid)
  286. Logger.features.Warn(
  287. $"Feature not valid on {plugin.Item1.Name}: {featureObj.InvalidMessage}");
  288. plugin.Item2.RemoveAt(i--);
  289. }
  290. else
  291. {
  292. Logger.features.Error($"Error parsing feature definition on {plugin.Item1.Name}");
  293. Logger.features.Error(exception);
  294. plugin.Item2.RemoveAt(i--);
  295. }
  296. }
  297. foreach (var plugin in PluginsMetadata)
  298. foreach (var feature in plugin.Features)
  299. feature.Evaluate();
  300. }
  301. foreach (var plugin in parsedFeatures)
  302. {
  303. if (plugin.Item2.Count <= 0) continue;
  304. Logger.features.Warn($"On plugin {plugin.Item1.Name}:");
  305. foreach (var feature in plugin.Item2)
  306. Logger.features.Warn($" Feature not found with name {feature.Item1}");
  307. }
  308. }
  309. internal static void Load(PluginMetadata meta)
  310. {
  311. if (meta.Assembly == null)
  312. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  313. }
  314. internal static PluginInfo InitPlugin(PluginMetadata meta)
  315. {
  316. if (meta.PluginType == null)
  317. return new PluginInfo()
  318. {
  319. Metadata = meta,
  320. Plugin = null
  321. };
  322. var info = new PluginInfo();
  323. try
  324. {
  325. Load(meta);
  326. Feature denyingFeature = null;
  327. if (!meta.Features.All(f => (denyingFeature = f).BeforeLoad(meta)))
  328. {
  329. Logger.loader.Warn(
  330. $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from loading! {denyingFeature?.InvalidMessage}");
  331. return null;
  332. }
  333. var type = meta.Assembly.GetType(meta.PluginType.FullName);
  334. var instance = (IBeatSaberPlugin)Activator.CreateInstance(type);
  335. info.Metadata = meta;
  336. info.Plugin = instance;
  337. var init = type.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public);
  338. if (init != null)
  339. {
  340. denyingFeature = null;
  341. if (!meta.Features.All(f => (denyingFeature = f).BeforeInit(info)))
  342. {
  343. Logger.loader.Warn(
  344. $"Feature {denyingFeature?.GetType()} denied plugin {meta.Name} from initializing! {denyingFeature?.InvalidMessage}");
  345. return null;
  346. }
  347. PluginInitInjector.Inject(init, info);
  348. }
  349. foreach (var feature in meta.Features)
  350. try
  351. {
  352. feature.AfterInit(info);
  353. }
  354. catch (Exception e)
  355. {
  356. Logger.loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}: {e}");
  357. }
  358. }
  359. catch (AmbiguousMatchException)
  360. {
  361. Logger.loader.Error($"Only one Init allowed per plugin (ambiguous match in {meta.Name})");
  362. return null;
  363. }
  364. catch (Exception e)
  365. {
  366. Logger.loader.Error($"Could not init plugin {meta.Name}: {e}");
  367. return null;
  368. }
  369. return info;
  370. }
  371. internal static List<PluginInfo> LoadPlugins() => PluginsMetadata.Select(InitPlugin).Where(p => p != null).ToList();
  372. }
  373. }