PluginManager.cs 26 KB

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