PluginManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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.Plugins
  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. plugin = new LocalPlugin(
  390. pInstance.AssemblyFilePath,
  391. true,
  392. new PluginManifest
  393. {
  394. Guid = pInstance.Id,
  395. Status = PluginStatus.Active,
  396. Name = pInstance.Name,
  397. Version = pInstance.Version.ToString(),
  398. MaxAbi = _nextVersion.ToString()
  399. })
  400. {
  401. Instance = pInstance
  402. };
  403. _plugins.Add(plugin);
  404. plugin.Manifest.Status = PluginStatus.Active;
  405. }
  406. else
  407. {
  408. plugin.Instance = instance;
  409. var manifest = plugin.Manifest;
  410. var pluginStr = plugin.Instance.Version.ToString();
  411. bool changed = false;
  412. if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal))
  413. {
  414. // If a plugin without a manifest failed to load due to an external issue (eg config),
  415. // this updates the manifest to the actual plugin values.
  416. manifest.Version = pluginStr;
  417. manifest.Name = plugin.Instance.Name;
  418. manifest.Description = plugin.Instance.Description;
  419. changed = true;
  420. }
  421. changed = changed || manifest.Status != PluginStatus.Active;
  422. manifest.Status = PluginStatus.Active;
  423. if (changed)
  424. {
  425. SaveManifest(manifest, plugin.Path);
  426. }
  427. }
  428. _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  429. return instance;
  430. }
  431. #pragma warning disable CA1031 // Do not catch general exception types
  432. catch (Exception ex)
  433. #pragma warning restore CA1031 // Do not catch general exception types
  434. {
  435. _logger.LogError(ex, "Error creating {Type}", type.FullName);
  436. if (plugin != null)
  437. {
  438. if (ChangePluginState(plugin, PluginStatus.Malfunctioned))
  439. {
  440. _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
  441. return null;
  442. }
  443. }
  444. _logger.LogDebug("Unable to auto-disable.");
  445. return null;
  446. }
  447. }
  448. private void CheckIfStillSuperceded(LocalPlugin plugin)
  449. {
  450. if (plugin.Manifest.Status != PluginStatus.Superceded)
  451. {
  452. return;
  453. }
  454. var predecessor = _plugins.OrderByDescending(p => p.Version)
  455. .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
  456. if (predecessor != null)
  457. {
  458. return;
  459. }
  460. plugin.Manifest.Status = PluginStatus.Active;
  461. }
  462. /// <summary>
  463. /// Attempts to delete a plugin.
  464. /// </summary>
  465. /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
  466. /// <returns>True if successful.</returns>
  467. private bool DeletePlugin(LocalPlugin plugin)
  468. {
  469. // Attempt a cleanup of old folders.
  470. try
  471. {
  472. Directory.Delete(plugin.Path, true);
  473. _logger.LogDebug("Deleted {Path}", plugin.Path);
  474. _plugins.Remove(plugin);
  475. }
  476. #pragma warning disable CA1031 // Do not catch general exception types
  477. catch
  478. #pragma warning restore CA1031 // Do not catch general exception types
  479. {
  480. return false;
  481. }
  482. return _plugins.Remove(plugin);
  483. }
  484. private LocalPlugin? LoadManifest(string dir)
  485. {
  486. try
  487. {
  488. Version? version;
  489. PluginManifest? manifest = null;
  490. var metafile = Path.Combine(dir, "meta.json");
  491. if (File.Exists(metafile))
  492. {
  493. try
  494. {
  495. var data = File.ReadAllText(metafile, Encoding.UTF8);
  496. manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
  497. }
  498. #pragma warning disable CA1031 // Do not catch general exception types
  499. catch (Exception ex)
  500. #pragma warning restore CA1031 // Do not catch general exception types
  501. {
  502. _logger.LogError(ex, "Error deserializing {Path}.", dir);
  503. }
  504. }
  505. if (manifest != null)
  506. {
  507. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  508. {
  509. targetAbi = _minimumVersion;
  510. }
  511. if (!Version.TryParse(manifest.MaxAbi, out var maxAbi))
  512. {
  513. maxAbi = _appVersion;
  514. }
  515. if (!Version.TryParse(manifest.Version, out version))
  516. {
  517. manifest.Version = _minimumVersion.ToString();
  518. }
  519. return new LocalPlugin(dir, _appVersion >= targetAbi && _appVersion <= maxAbi, manifest);
  520. }
  521. // No metafile, so lets see if the folder is versioned.
  522. // TODO: Phase this support out in future versions.
  523. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  524. int versionIndex = dir.LastIndexOf('_');
  525. if (versionIndex != -1)
  526. {
  527. // Get the version number from the filename if possible.
  528. metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex];
  529. version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
  530. }
  531. else
  532. {
  533. // Un-versioned folder - Add it under the path name and version it suitable for this instance.
  534. version = _appVersion;
  535. }
  536. // Auto-create a plugin manifest, so we can disable it, if it fails to load.
  537. manifest = new PluginManifest
  538. {
  539. Status = PluginStatus.Restart,
  540. Name = metafile,
  541. AutoUpdate = false,
  542. Guid = metafile.GetMD5(),
  543. TargetAbi = _appVersion.ToString(),
  544. Version = version.ToString()
  545. };
  546. return new LocalPlugin(dir, true, manifest);
  547. }
  548. #pragma warning disable CA1031 // Do not catch general exception types
  549. catch (Exception ex)
  550. #pragma warning restore CA1031 // Do not catch general exception types
  551. {
  552. _logger.LogError(ex, "Something went wrong!");
  553. return null;
  554. }
  555. }
  556. /// <summary>
  557. /// Gets the list of local plugins.
  558. /// </summary>
  559. /// <returns>Enumerable of local plugins.</returns>
  560. private IEnumerable<LocalPlugin> DiscoverPlugins()
  561. {
  562. var versions = new List<LocalPlugin>();
  563. if (!Directory.Exists(_pluginsPath))
  564. {
  565. // Plugin path doesn't exist, don't try to enumerate sub-folders.
  566. return Enumerable.Empty<LocalPlugin>();
  567. }
  568. var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
  569. LocalPlugin? entry;
  570. foreach (var dir in directories)
  571. {
  572. entry = LoadManifest(dir);
  573. if (entry != null)
  574. {
  575. versions.Add(entry);
  576. }
  577. }
  578. string lastName = string.Empty;
  579. versions.Sort(LocalPlugin.Compare);
  580. // Traverse backwards through the list.
  581. // The first item will be the latest version.
  582. for (int x = versions.Count - 1; x >= 0; x--)
  583. {
  584. entry = versions[x];
  585. if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
  586. {
  587. entry.DllFiles.AddRange(Directory.EnumerateFiles(entry.Path, "*.dll", SearchOption.AllDirectories));
  588. if (entry.IsEnabledAndSupported)
  589. {
  590. lastName = entry.Name;
  591. continue;
  592. }
  593. }
  594. if (string.IsNullOrEmpty(lastName))
  595. {
  596. continue;
  597. }
  598. var manifest = entry.Manifest;
  599. var cleaned = false;
  600. var path = entry.Path;
  601. if (_config.RemoveOldPlugins)
  602. {
  603. // Attempt a cleanup of old folders.
  604. try
  605. {
  606. _logger.LogDebug("Deleting {Path}", path);
  607. Directory.Delete(path, true);
  608. cleaned = true;
  609. }
  610. #pragma warning disable CA1031 // Do not catch general exception types
  611. catch (Exception e)
  612. #pragma warning restore CA1031 // Do not catch general exception types
  613. {
  614. _logger.LogWarning(e, "Unable to delete {Path}", path);
  615. }
  616. if (cleaned)
  617. {
  618. versions.RemoveAt(x);
  619. }
  620. else
  621. {
  622. if (manifest == null)
  623. {
  624. _logger.LogWarning("Unable to disable plugin {Path}", entry.Path);
  625. continue;
  626. }
  627. if (manifest.Status != PluginStatus.Deleted)
  628. {
  629. manifest.Status = PluginStatus.Deleted;
  630. SaveManifest(manifest, entry.Path);
  631. }
  632. }
  633. }
  634. }
  635. // Only want plugin folders which have files.
  636. return versions.Where(p => p.DllFiles.Count != 0);
  637. }
  638. }
  639. }