PluginManager.cs 26 KB

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