PluginManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.Http;
  7. using System.Reflection;
  8. using System.Runtime.Loader;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Threading.Tasks;
  12. using Jellyfin.Extensions.Json;
  13. using Jellyfin.Extensions.Json.Converters;
  14. using MediaBrowser.Common;
  15. using MediaBrowser.Common.Extensions;
  16. using MediaBrowser.Common.Net;
  17. using MediaBrowser.Common.Plugins;
  18. using MediaBrowser.Model.Configuration;
  19. using MediaBrowser.Model.IO;
  20. using MediaBrowser.Model.Plugins;
  21. using MediaBrowser.Model.Updates;
  22. using Microsoft.Extensions.DependencyInjection;
  23. using Microsoft.Extensions.Logging;
  24. namespace Emby.Server.Implementations.Plugins
  25. {
  26. /// <summary>
  27. /// Defines the <see cref="PluginManager" />.
  28. /// </summary>
  29. public class PluginManager : IPluginManager
  30. {
  31. private readonly string _pluginsPath;
  32. private readonly Version _appVersion;
  33. private readonly List<AssemblyLoadContext> _assemblyLoadContexts;
  34. private readonly JsonSerializerOptions _jsonOptions;
  35. private readonly ILogger<PluginManager> _logger;
  36. private readonly IApplicationHost _appHost;
  37. private readonly ServerConfiguration _config;
  38. private readonly List<LocalPlugin> _plugins;
  39. private readonly Version _minimumVersion;
  40. private IHttpClientFactory? _httpClientFactory;
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="PluginManager"/> class.
  43. /// </summary>
  44. /// <param name="logger">The <see cref="ILogger"/>.</param>
  45. /// <param name="appHost">The <see cref="IApplicationHost"/>.</param>
  46. /// <param name="config">The <see cref="ServerConfiguration"/>.</param>
  47. /// <param name="pluginsPath">The plugin path.</param>
  48. /// <param name="appVersion">The application version.</param>
  49. public PluginManager(
  50. ILogger<PluginManager> logger,
  51. IApplicationHost appHost,
  52. ServerConfiguration config,
  53. string pluginsPath,
  54. Version appVersion)
  55. {
  56. _logger = logger ?? throw new ArgumentNullException(nameof(logger));
  57. _pluginsPath = pluginsPath;
  58. _appVersion = appVersion ?? throw new ArgumentNullException(nameof(appVersion));
  59. _jsonOptions = new JsonSerializerOptions(JsonDefaults.Options)
  60. {
  61. WriteIndented = true
  62. };
  63. // We need to use the default GUID converter, so we need to remove any custom ones.
  64. for (int a = _jsonOptions.Converters.Count - 1; a >= 0; a--)
  65. {
  66. if (_jsonOptions.Converters[a] is JsonGuidConverter convertor)
  67. {
  68. _jsonOptions.Converters.Remove(convertor);
  69. break;
  70. }
  71. }
  72. _config = config;
  73. _appHost = appHost;
  74. _minimumVersion = new Version(0, 0, 0, 1);
  75. _plugins = Directory.Exists(_pluginsPath) ? DiscoverPlugins().ToList() : new List<LocalPlugin>();
  76. _assemblyLoadContexts = new List<AssemblyLoadContext>();
  77. }
  78. private IHttpClientFactory HttpClientFactory
  79. {
  80. get
  81. {
  82. return _httpClientFactory ??= _appHost.Resolve<IHttpClientFactory>();
  83. }
  84. }
  85. /// <summary>
  86. /// Gets the Plugins.
  87. /// </summary>
  88. public IReadOnlyList<LocalPlugin> Plugins => _plugins;
  89. /// <summary>
  90. /// Returns all the assemblies.
  91. /// </summary>
  92. /// <returns>An IEnumerable{Assembly}.</returns>
  93. public IEnumerable<Assembly> LoadAssemblies()
  94. {
  95. // Attempt to remove any deleted plugins and change any successors to be active.
  96. for (int i = _plugins.Count - 1; i >= 0; i--)
  97. {
  98. var plugin = _plugins[i];
  99. if (plugin.Manifest.Status == PluginStatus.Deleted && DeletePlugin(plugin))
  100. {
  101. // See if there is another version, and if so make that active.
  102. ProcessAlternative(plugin);
  103. }
  104. }
  105. // Now load the assemblies..
  106. foreach (var plugin in _plugins)
  107. {
  108. UpdatePluginSuperceedStatus(plugin);
  109. if (plugin.IsEnabledAndSupported == false)
  110. {
  111. _logger.LogInformation("Skipping disabled plugin {Version} of {Name} ", plugin.Version, plugin.Name);
  112. continue;
  113. }
  114. var assemblyLoadContext = new PluginLoadContext(plugin.Path);
  115. _assemblyLoadContexts.Add(assemblyLoadContext);
  116. var assemblies = new List<Assembly>(plugin.DllFiles.Count);
  117. var loadedAll = true;
  118. foreach (var file in plugin.DllFiles)
  119. {
  120. try
  121. {
  122. assemblies.Add(assemblyLoadContext.LoadFromAssemblyPath(file));
  123. }
  124. catch (FileLoadException ex)
  125. {
  126. _logger.LogError(ex, "Failed to load assembly {Path}. Disabling plugin", file);
  127. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  128. loadedAll = false;
  129. break;
  130. }
  131. #pragma warning disable CA1031 // Do not catch general exception types
  132. catch (Exception ex)
  133. #pragma warning restore CA1031 // Do not catch general exception types
  134. {
  135. _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling plugin", file);
  136. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  137. loadedAll = false;
  138. break;
  139. }
  140. }
  141. if (!loadedAll)
  142. {
  143. continue;
  144. }
  145. foreach (var assembly in assemblies)
  146. {
  147. try
  148. {
  149. // Load all required types to verify that the plugin will load
  150. assembly.GetTypes();
  151. }
  152. catch (SystemException ex) when (ex is TypeLoadException or ReflectionTypeLoadException) // Undocumented exception
  153. {
  154. _logger.LogError(ex, "Failed to load assembly {Path}. This error occurs when a plugin references an incompatible version of one of the shared libraries. Disabling plugin", assembly.Location);
  155. ChangePluginState(plugin, PluginStatus.NotSupported);
  156. break;
  157. }
  158. #pragma warning disable CA1031 // Do not catch general exception types
  159. catch (Exception ex)
  160. #pragma warning restore CA1031 // Do not catch general exception types
  161. {
  162. _logger.LogError(ex, "Failed to load assembly {Path}. Unknown exception was thrown. Disabling plugin", assembly.Location);
  163. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  164. break;
  165. }
  166. _logger.LogInformation("Loaded assembly {Assembly} from {Path}", assembly.FullName, assembly.Location);
  167. yield return assembly;
  168. }
  169. }
  170. }
  171. /// <inheritdoc />
  172. public void UnloadAssemblies()
  173. {
  174. foreach (var assemblyLoadContext in _assemblyLoadContexts)
  175. {
  176. assemblyLoadContext.Unload();
  177. }
  178. }
  179. /// <summary>
  180. /// Creates all the plugin instances.
  181. /// </summary>
  182. public void CreatePlugins()
  183. {
  184. _ = _appHost.GetExports<IPlugin>(CreatePluginInstance);
  185. }
  186. /// <summary>
  187. /// Registers the plugin's services with the DI.
  188. /// Note: DI is not yet instantiated yet.
  189. /// </summary>
  190. /// <param name="serviceCollection">A <see cref="ServiceCollection"/> instance.</param>
  191. public void RegisterServices(IServiceCollection serviceCollection)
  192. {
  193. foreach (var pluginServiceRegistrator in _appHost.GetExportTypes<IPluginServiceRegistrator>())
  194. {
  195. var plugin = GetPluginByAssembly(pluginServiceRegistrator.Assembly);
  196. if (plugin is null)
  197. {
  198. _logger.LogError("Unable to find plugin in assembly {Assembly}", pluginServiceRegistrator.Assembly.FullName);
  199. continue;
  200. }
  201. UpdatePluginSuperceedStatus(plugin);
  202. if (!plugin.IsEnabledAndSupported)
  203. {
  204. continue;
  205. }
  206. try
  207. {
  208. var instance = (IPluginServiceRegistrator?)Activator.CreateInstance(pluginServiceRegistrator);
  209. instance?.RegisterServices(serviceCollection);
  210. }
  211. #pragma warning disable CA1031 // Do not catch general exception types
  212. catch (Exception ex)
  213. #pragma warning restore CA1031 // Do not catch general exception types
  214. {
  215. _logger.LogError(ex, "Error registering plugin services from {Assembly}.", pluginServiceRegistrator.Assembly.FullName);
  216. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  217. {
  218. _logger.LogInformation("Disabling plugin {Path}", plugin.Path);
  219. }
  220. }
  221. }
  222. }
  223. /// <summary>
  224. /// Imports a plugin manifest from <paramref name="folder"/>.
  225. /// </summary>
  226. /// <param name="folder">Folder of the plugin.</param>
  227. public void ImportPluginFrom(string folder)
  228. {
  229. ArgumentException.ThrowIfNullOrEmpty(folder);
  230. // Load the plugin.
  231. var plugin = LoadManifest(folder);
  232. // Make sure we haven't already loaded this.
  233. if (_plugins.Any(p => p.Manifest.Equals(plugin.Manifest)))
  234. {
  235. return;
  236. }
  237. _plugins.Add(plugin);
  238. EnablePlugin(plugin);
  239. }
  240. /// <summary>
  241. /// Removes the plugin reference '<paramref name="plugin"/>.
  242. /// </summary>
  243. /// <param name="plugin">The plugin.</param>
  244. /// <returns>Outcome of the operation.</returns>
  245. public bool RemovePlugin(LocalPlugin plugin)
  246. {
  247. ArgumentNullException.ThrowIfNull(plugin);
  248. if (DeletePlugin(plugin))
  249. {
  250. ProcessAlternative(plugin);
  251. return true;
  252. }
  253. _logger.LogWarning("Unable to delete {Path}, so marking as deleteOnStartup.", plugin.Path);
  254. // Unable to delete, so disable.
  255. if (ChangePluginState(plugin, PluginStatus.Deleted))
  256. {
  257. ProcessAlternative(plugin);
  258. return true;
  259. }
  260. return false;
  261. }
  262. /// <summary>
  263. /// Attempts to find the plugin with and id of <paramref name="id"/>.
  264. /// </summary>
  265. /// <param name="id">The <see cref="Guid"/> of plugin.</param>
  266. /// <param name="version">Optional <see cref="Version"/> of the plugin to locate.</param>
  267. /// <returns>A <see cref="LocalPlugin"/> if located, or null if not.</returns>
  268. public LocalPlugin? GetPlugin(Guid id, Version? version = null)
  269. {
  270. LocalPlugin? plugin;
  271. if (version is null)
  272. {
  273. // If no version is given, return the current instance.
  274. var plugins = _plugins.Where(p => p.Id.Equals(id)).ToList();
  275. plugin = plugins.FirstOrDefault(p => p.Instance is not null) ?? plugins.MaxBy(p => p.Version);
  276. }
  277. else
  278. {
  279. // Match id and version number.
  280. plugin = _plugins.FirstOrDefault(p => p.Id.Equals(id) && p.Version.Equals(version));
  281. }
  282. return plugin;
  283. }
  284. /// <summary>
  285. /// Enables the plugin, disabling all other versions.
  286. /// </summary>
  287. /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
  288. public void EnablePlugin(LocalPlugin plugin)
  289. {
  290. ArgumentNullException.ThrowIfNull(plugin);
  291. if (ChangePluginState(plugin, PluginStatus.Active))
  292. {
  293. // See if there is another version, and if so, supercede it.
  294. ProcessAlternative(plugin);
  295. }
  296. }
  297. /// <summary>
  298. /// Disable the plugin.
  299. /// </summary>
  300. /// <param name="plugin">The <see cref="LocalPlugin"/> of the plug to disable.</param>
  301. public void DisablePlugin(LocalPlugin plugin)
  302. {
  303. ArgumentNullException.ThrowIfNull(plugin);
  304. // Update the manifest on disk
  305. if (ChangePluginState(plugin, PluginStatus.Disabled))
  306. {
  307. // If there is another version, activate it.
  308. ProcessAlternative(plugin);
  309. }
  310. }
  311. /// <summary>
  312. /// Disable the plugin.
  313. /// </summary>
  314. /// <param name="assembly">The <see cref="Assembly"/> of the plug to disable.</param>
  315. public void FailPlugin(Assembly assembly)
  316. {
  317. // Only save if disabled.
  318. ArgumentNullException.ThrowIfNull(assembly);
  319. var plugin = _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location));
  320. if (plugin is null)
  321. {
  322. // A plugin's assembly didn't cause this issue, so ignore it.
  323. return;
  324. }
  325. ChangePluginState(plugin, PluginStatus.Malfunctioned);
  326. }
  327. /// <inheritdoc/>
  328. public bool SaveManifest(PluginManifest manifest, string path)
  329. {
  330. try
  331. {
  332. var data = JsonSerializer.Serialize(manifest, _jsonOptions);
  333. File.WriteAllText(Path.Combine(path, "meta.json"), data);
  334. return true;
  335. }
  336. catch (ArgumentException e)
  337. {
  338. _logger.LogWarning(e, "Unable to save plugin manifest due to invalid value. {Path}", path);
  339. return false;
  340. }
  341. }
  342. /// <inheritdoc/>
  343. public async Task<bool> GenerateManifest(PackageInfo packageInfo, Version version, string path, PluginStatus status)
  344. {
  345. var versionInfo = packageInfo.Versions.First(v => v.Version == version.ToString());
  346. var imagePath = string.Empty;
  347. if (!string.IsNullOrEmpty(packageInfo.ImageUrl))
  348. {
  349. var url = new Uri(packageInfo.ImageUrl);
  350. imagePath = Path.Join(path, url.Segments[^1]);
  351. await using var fileStream = AsyncFile.OpenWrite(imagePath);
  352. try
  353. {
  354. await using var downloadStream = await HttpClientFactory
  355. .CreateClient(NamedClient.Default)
  356. .GetStreamAsync(url)
  357. .ConfigureAwait(false);
  358. await downloadStream.CopyToAsync(fileStream).ConfigureAwait(false);
  359. }
  360. catch (HttpRequestException ex)
  361. {
  362. _logger.LogError(ex, "Failed to download image to path {Path} on disk.", imagePath);
  363. imagePath = string.Empty;
  364. }
  365. }
  366. var manifest = new PluginManifest
  367. {
  368. Category = packageInfo.Category,
  369. Changelog = versionInfo.Changelog ?? string.Empty,
  370. Description = packageInfo.Description,
  371. Id = packageInfo.Id,
  372. Name = packageInfo.Name,
  373. Overview = packageInfo.Overview,
  374. Owner = packageInfo.Owner,
  375. TargetAbi = versionInfo.TargetAbi ?? string.Empty,
  376. Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp, CultureInfo.InvariantCulture),
  377. Version = versionInfo.Version,
  378. Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state.
  379. AutoUpdate = true,
  380. ImagePath = imagePath
  381. };
  382. return SaveManifest(manifest, path);
  383. }
  384. /// <summary>
  385. /// Changes a plugin's load status.
  386. /// </summary>
  387. /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
  388. /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
  389. /// <returns>Success of the task.</returns>
  390. private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
  391. {
  392. if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
  393. {
  394. // No need to save as the state hasn't changed.
  395. return true;
  396. }
  397. plugin.Manifest.Status = state;
  398. return SaveManifest(plugin.Manifest, plugin.Path);
  399. }
  400. /// <summary>
  401. /// Finds the plugin record using the assembly.
  402. /// </summary>
  403. /// <param name="assembly">The <see cref="Assembly"/> being sought.</param>
  404. /// <returns>The matching record, or null if not found.</returns>
  405. private LocalPlugin? GetPluginByAssembly(Assembly assembly)
  406. {
  407. // Find which plugin it is by the path.
  408. return _plugins.FirstOrDefault(p => p.DllFiles.Contains(assembly.Location, StringComparer.Ordinal));
  409. }
  410. /// <summary>
  411. /// Creates the instance safe.
  412. /// </summary>
  413. /// <param name="type">The type.</param>
  414. /// <returns>System.Object.</returns>
  415. private IPlugin? CreatePluginInstance(Type type)
  416. {
  417. // Find the record for this plugin.
  418. var plugin = GetPluginByAssembly(type.Assembly);
  419. if (plugin?.Manifest.Status < PluginStatus.Active)
  420. {
  421. return null;
  422. }
  423. try
  424. {
  425. _logger.LogDebug("Creating instance of {Type}", type);
  426. // _appHost.ServiceProvider is already assigned when we create the plugins
  427. var instance = (IPlugin)ActivatorUtilities.CreateInstance(_appHost.ServiceProvider!, type);
  428. if (plugin is null)
  429. {
  430. // Create a dummy record for the providers.
  431. // TODO: remove this code once all provided have been released as separate plugins.
  432. plugin = new LocalPlugin(
  433. instance.AssemblyFilePath,
  434. true,
  435. new PluginManifest
  436. {
  437. Id = instance.Id,
  438. Status = PluginStatus.Active,
  439. Name = instance.Name,
  440. Version = instance.Version.ToString()
  441. })
  442. {
  443. Instance = instance
  444. };
  445. _plugins.Add(plugin);
  446. plugin.Manifest.Status = PluginStatus.Active;
  447. }
  448. else
  449. {
  450. plugin.Instance = instance;
  451. var manifest = plugin.Manifest;
  452. var pluginStr = instance.Version.ToString();
  453. bool changed = false;
  454. if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal)
  455. || !manifest.Id.Equals(instance.Id))
  456. {
  457. // If a plugin without a manifest failed to load due to an external issue (eg config),
  458. // this updates the manifest to the actual plugin values.
  459. manifest.Version = pluginStr;
  460. manifest.Name = plugin.Instance.Name;
  461. manifest.Description = plugin.Instance.Description;
  462. manifest.Id = plugin.Instance.Id;
  463. changed = true;
  464. }
  465. changed = changed || manifest.Status != PluginStatus.Active;
  466. manifest.Status = PluginStatus.Active;
  467. if (changed)
  468. {
  469. SaveManifest(manifest, plugin.Path);
  470. }
  471. }
  472. _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  473. return instance;
  474. }
  475. #pragma warning disable CA1031 // Do not catch general exception types
  476. catch (Exception ex)
  477. #pragma warning restore CA1031 // Do not catch general exception types
  478. {
  479. _logger.LogError(ex, "Error creating {Type}", type.FullName);
  480. if (plugin is not null)
  481. {
  482. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  483. {
  484. _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
  485. return null;
  486. }
  487. }
  488. _logger.LogDebug("Unable to auto-disable.");
  489. return null;
  490. }
  491. }
  492. private void UpdatePluginSuperceedStatus(LocalPlugin plugin)
  493. {
  494. if (plugin.Manifest.Status != PluginStatus.Superceded)
  495. {
  496. return;
  497. }
  498. var predecessor = _plugins.OrderByDescending(p => p.Version)
  499. .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
  500. if (predecessor is not null)
  501. {
  502. return;
  503. }
  504. plugin.Manifest.Status = PluginStatus.Active;
  505. }
  506. /// <summary>
  507. /// Attempts to delete a plugin.
  508. /// </summary>
  509. /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
  510. /// <returns>True if successful.</returns>
  511. private bool DeletePlugin(LocalPlugin plugin)
  512. {
  513. // Attempt a cleanup of old folders.
  514. try
  515. {
  516. Directory.Delete(plugin.Path, true);
  517. _logger.LogDebug("Deleted {Path}", plugin.Path);
  518. }
  519. #pragma warning disable CA1031 // Do not catch general exception types
  520. catch
  521. #pragma warning restore CA1031 // Do not catch general exception types
  522. {
  523. return false;
  524. }
  525. return _plugins.Remove(plugin);
  526. }
  527. internal LocalPlugin LoadManifest(string dir)
  528. {
  529. Version? version;
  530. PluginManifest? manifest = null;
  531. var metafile = Path.Combine(dir, "meta.json");
  532. if (File.Exists(metafile))
  533. {
  534. // Only path where this stays null is when File.ReadAllBytes throws an IOException
  535. byte[] data = null!;
  536. try
  537. {
  538. data = File.ReadAllBytes(metafile);
  539. manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
  540. }
  541. catch (IOException ex)
  542. {
  543. _logger.LogError(ex, "Error reading file {Path}.", dir);
  544. }
  545. catch (JsonException ex)
  546. {
  547. _logger.LogError(ex, "Error deserializing {Json}.", Encoding.UTF8.GetString(data!));
  548. }
  549. if (manifest is not null)
  550. {
  551. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  552. {
  553. targetAbi = _minimumVersion;
  554. }
  555. if (!Version.TryParse(manifest.Version, out version))
  556. {
  557. manifest.Version = _minimumVersion.ToString();
  558. }
  559. return new LocalPlugin(dir, _appVersion >= targetAbi, manifest);
  560. }
  561. }
  562. // No metafile, so lets see if the folder is versioned.
  563. // TODO: Phase this support out in future versions.
  564. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  565. int versionIndex = dir.LastIndexOf('_');
  566. if (versionIndex != -1)
  567. {
  568. // Get the version number from the filename if possible.
  569. metafile = Path.GetFileName(dir[..versionIndex]);
  570. version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
  571. }
  572. else
  573. {
  574. // Un-versioned folder - Add it under the path name and version it suitable for this instance.
  575. version = _appVersion;
  576. }
  577. // Auto-create a plugin manifest, so we can disable it, if it fails to load.
  578. manifest = new PluginManifest
  579. {
  580. Status = PluginStatus.Active,
  581. Name = metafile,
  582. AutoUpdate = false,
  583. Id = metafile.GetMD5(),
  584. TargetAbi = _appVersion.ToString(),
  585. Version = version.ToString()
  586. };
  587. return new LocalPlugin(dir, true, manifest);
  588. }
  589. /// <summary>
  590. /// Gets the list of local plugins.
  591. /// </summary>
  592. /// <returns>Enumerable of local plugins.</returns>
  593. private IEnumerable<LocalPlugin> DiscoverPlugins()
  594. {
  595. var versions = new List<LocalPlugin>();
  596. if (!Directory.Exists(_pluginsPath))
  597. {
  598. // Plugin path doesn't exist, don't try to enumerate sub-folders.
  599. return Enumerable.Empty<LocalPlugin>();
  600. }
  601. var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
  602. foreach (var dir in directories)
  603. {
  604. versions.Add(LoadManifest(dir));
  605. }
  606. string lastName = string.Empty;
  607. versions.Sort(LocalPlugin.Compare);
  608. // Traverse backwards through the list.
  609. // The first item will be the latest version.
  610. for (int x = versions.Count - 1; x >= 0; x--)
  611. {
  612. var entry = versions[x];
  613. if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
  614. {
  615. entry.DllFiles = Directory.GetFiles(entry.Path, "*.dll", SearchOption.AllDirectories);
  616. if (entry.IsEnabledAndSupported)
  617. {
  618. lastName = entry.Name;
  619. continue;
  620. }
  621. }
  622. if (string.IsNullOrEmpty(lastName))
  623. {
  624. continue;
  625. }
  626. var cleaned = false;
  627. var path = entry.Path;
  628. if (_config.RemoveOldPlugins)
  629. {
  630. // Attempt a cleanup of old folders.
  631. try
  632. {
  633. _logger.LogDebug("Deleting {Path}", path);
  634. Directory.Delete(path, true);
  635. cleaned = true;
  636. }
  637. #pragma warning disable CA1031 // Do not catch general exception types
  638. catch (Exception e)
  639. #pragma warning restore CA1031 // Do not catch general exception types
  640. {
  641. _logger.LogWarning(e, "Unable to delete {Path}", path);
  642. }
  643. if (cleaned)
  644. {
  645. versions.RemoveAt(x);
  646. }
  647. else
  648. {
  649. ChangePluginState(entry, PluginStatus.Deleted);
  650. }
  651. }
  652. }
  653. // Only want plugin folders which have files.
  654. return versions.Where(p => p.DllFiles.Count != 0);
  655. }
  656. /// <summary>
  657. /// Changes the status of the other versions of the plugin to "Superceded".
  658. /// </summary>
  659. /// <param name="plugin">The <see cref="LocalPlugin"/> that's master.</param>
  660. private void ProcessAlternative(LocalPlugin plugin)
  661. {
  662. // Detect whether there is another version of this plugin that needs disabling.
  663. var previousVersion = _plugins.OrderByDescending(p => p.Version)
  664. .FirstOrDefault(
  665. p => p.Id.Equals(plugin.Id)
  666. && p.IsEnabledAndSupported
  667. && p.Version != plugin.Version);
  668. if (previousVersion is null)
  669. {
  670. // This value is memory only - so that the web will show restart required.
  671. plugin.Manifest.Status = PluginStatus.Restart;
  672. plugin.Manifest.AutoUpdate = false;
  673. return;
  674. }
  675. if (plugin.Manifest.Status == PluginStatus.Active && !ChangePluginState(previousVersion, PluginStatus.Superceded))
  676. {
  677. _logger.LogError("Unable to enable version {Version} of {Name}", previousVersion.Version, previousVersion.Name);
  678. }
  679. else if (plugin.Manifest.Status == PluginStatus.Superceded && !ChangePluginState(previousVersion, PluginStatus.Active))
  680. {
  681. _logger.LogError("Unable to supercede version {Version} of {Name}", previousVersion.Version, previousVersion.Name);
  682. }
  683. // This value is memory only - so that the web will show restart required.
  684. plugin.Manifest.Status = PluginStatus.Restart;
  685. plugin.Manifest.AutoUpdate = false;
  686. }
  687. }
  688. }