PluginManager.cs 28 KB

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