PluginManager.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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 (!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(p => assembly.Equals(p.Assembly)).FirstOrDefault();
  286. if (plugin == null)
  287. {
  288. // A plugin's assembly didn't cause this issue, so ignore it.
  289. return;
  290. }
  291. ChangePluginState(plugin, PluginStatus.Malfunction);
  292. }
  293. /// <summary>
  294. /// Saves the manifest back to disk.
  295. /// </summary>
  296. /// <param name="manifest">The <see cref="PluginManifest"/> to save.</param>
  297. /// <param name="path">The path where to save the manifest.</param>
  298. /// <returns>True if successful.</returns>
  299. public bool SaveManifest(PluginManifest manifest, string path)
  300. {
  301. if (manifest == null)
  302. {
  303. return false;
  304. }
  305. try
  306. {
  307. var data = JsonSerializer.Serialize(manifest, _jsonOptions);
  308. File.WriteAllText(Path.Combine(path, "meta.json"), data, Encoding.UTF8);
  309. return true;
  310. }
  311. #pragma warning disable CA1031 // Do not catch general exception types
  312. catch (Exception e)
  313. #pragma warning restore CA1031 // Do not catch general exception types
  314. {
  315. _logger.LogWarning(e, "Unable to save plugin manifest. {Path}", path);
  316. return false;
  317. }
  318. }
  319. /// <summary>
  320. /// Changes a plugin's load status.
  321. /// </summary>
  322. /// <param name="plugin">The <see cref="LocalPlugin"/> instance.</param>
  323. /// <param name="state">The <see cref="PluginStatus"/> of the plugin.</param>
  324. /// <returns>Success of the task.</returns>
  325. private bool ChangePluginState(LocalPlugin plugin, PluginStatus state)
  326. {
  327. if (plugin.Manifest.Status == state || string.IsNullOrEmpty(plugin.Path))
  328. {
  329. // No need to save as the state hasn't changed.
  330. return true;
  331. }
  332. plugin.Manifest.Status = state;
  333. SaveManifest(plugin.Manifest, plugin.Path);
  334. try
  335. {
  336. var data = JsonSerializer.Serialize(plugin.Manifest, _jsonOptions);
  337. File.WriteAllText(Path.Combine(plugin.Path, "meta.json"), data, Encoding.UTF8);
  338. return true;
  339. }
  340. #pragma warning disable CA1031 // Do not catch general exception types
  341. catch (Exception e)
  342. #pragma warning restore CA1031 // Do not catch general exception types
  343. {
  344. _logger.LogWarning(e, "Unable to disable plugin {Path}", plugin.Path);
  345. return false;
  346. }
  347. }
  348. /// <summary>
  349. /// Finds the plugin record using the type.
  350. /// </summary>
  351. /// <param name="type">The <see cref="Type"/> being sought.</param>
  352. /// <returns>The matching record, or null if not found.</returns>
  353. private LocalPlugin? GetPluginByType(Type type)
  354. {
  355. // Find which plugin it is by the path.
  356. return _plugins.FirstOrDefault(p => string.Equals(p.Path, Path.GetDirectoryName(type.Assembly.Location), StringComparison.Ordinal));
  357. }
  358. /// <summary>
  359. /// Creates the instance safe.
  360. /// </summary>
  361. /// <param name="type">The type.</param>
  362. /// <returns>System.Object.</returns>
  363. private object? CreatePluginInstance(Type type)
  364. {
  365. // Find the record for this plugin.
  366. var plugin = GetPluginByType(type);
  367. try
  368. {
  369. _logger.LogDebug("Creating instance of {Type}", type);
  370. var instance = ActivatorUtilities.CreateInstance(_appHost.ServiceProvider, type);
  371. if (plugin == null)
  372. {
  373. // Create a dummy record for the providers.
  374. var pInstance = (IPlugin)instance;
  375. plugin = new LocalPlugin(
  376. pInstance.AssemblyFilePath,
  377. true,
  378. new PluginManifest
  379. {
  380. Guid = pInstance.Id,
  381. Status = PluginStatus.Active,
  382. Name = pInstance.Name,
  383. Version = pInstance.Version.ToString(),
  384. MaxAbi = _nextVersion.ToString()
  385. })
  386. {
  387. Instance = pInstance
  388. };
  389. _plugins.Add(plugin);
  390. plugin.Manifest.Status = PluginStatus.Active;
  391. }
  392. else
  393. {
  394. plugin.Instance = (IPlugin)instance;
  395. var manifest = plugin.Manifest;
  396. var pluginStr = plugin.Instance.Version.ToString();
  397. if (string.Equals(manifest.Version, pluginStr, StringComparison.Ordinal))
  398. {
  399. // If a plugin without a manifest failed to load due to an external issue (eg config),
  400. // this updates the manifest to the actual plugin values.
  401. manifest.Version = pluginStr;
  402. manifest.Name = plugin.Instance.Name;
  403. manifest.Description = plugin.Instance.Description;
  404. }
  405. manifest.Status = PluginStatus.Active;
  406. SaveManifest(manifest, plugin.Path);
  407. }
  408. _logger.LogInformation("Loaded plugin: {PluginName} {PluginVersion}", plugin.Name, plugin.Version);
  409. return instance;
  410. }
  411. #pragma warning disable CA1031 // Do not catch general exception types
  412. catch (Exception ex)
  413. #pragma warning restore CA1031 // Do not catch general exception types
  414. {
  415. _logger.LogError(ex, "Error creating {Type}", type.FullName);
  416. if (plugin != null)
  417. {
  418. if (ChangePluginState(plugin, PluginStatus.Malfunction))
  419. {
  420. _logger.LogInformation("Plugin {Path} has been disabled.", plugin.Path);
  421. return null;
  422. }
  423. }
  424. _logger.LogDebug("Unable to auto-disable.");
  425. return null;
  426. }
  427. }
  428. private void CheckIfStillSuperceded(LocalPlugin plugin)
  429. {
  430. if (plugin.Manifest.Status != PluginStatus.Superceded)
  431. {
  432. return;
  433. }
  434. var predecessor = _plugins.OrderByDescending(p => p.Version)
  435. .FirstOrDefault(p => p.Id.Equals(plugin.Id) && p.IsEnabledAndSupported && p.Version != plugin.Version);
  436. if (predecessor != null)
  437. {
  438. return;
  439. }
  440. plugin.Manifest.Status = PluginStatus.Active;
  441. }
  442. /// <summary>
  443. /// Attempts to delete a plugin.
  444. /// </summary>
  445. /// <param name="plugin">A <see cref="LocalPlugin"/> instance to delete.</param>
  446. /// <returns>True if successful.</returns>
  447. private bool DeletePlugin(LocalPlugin plugin)
  448. {
  449. // Attempt a cleanup of old folders.
  450. try
  451. {
  452. _logger.LogDebug("Deleting {Path}", plugin.Path);
  453. Directory.Delete(plugin.Path, true);
  454. _plugins.Remove(plugin);
  455. }
  456. #pragma warning disable CA1031 // Do not catch general exception types
  457. catch (Exception e)
  458. #pragma warning restore CA1031 // Do not catch general exception types
  459. {
  460. _logger.LogWarning(e, "Unable to delete {Path}", plugin.Path);
  461. return false;
  462. }
  463. return _plugins.Remove(plugin);
  464. }
  465. private LocalPlugin? LoadManifest(string dir)
  466. {
  467. try
  468. {
  469. Version? version;
  470. PluginManifest? manifest = null;
  471. var metafile = Path.Combine(dir, "meta.json");
  472. if (File.Exists(metafile))
  473. {
  474. try
  475. {
  476. var data = File.ReadAllText(metafile, Encoding.UTF8);
  477. manifest = JsonSerializer.Deserialize<PluginManifest>(data, _jsonOptions);
  478. }
  479. #pragma warning disable CA1031 // Do not catch general exception types
  480. catch (Exception ex)
  481. #pragma warning restore CA1031 // Do not catch general exception types
  482. {
  483. _logger.LogError(ex, "Error deserializing {Path}.", dir);
  484. }
  485. }
  486. if (manifest != null)
  487. {
  488. if (!Version.TryParse(manifest.TargetAbi, out var targetAbi))
  489. {
  490. targetAbi = _minimumVersion;
  491. }
  492. if (!Version.TryParse(manifest.MaxAbi, out var maxAbi))
  493. {
  494. maxAbi = _appVersion;
  495. }
  496. if (!Version.TryParse(manifest.Version, out version))
  497. {
  498. manifest.Version = _minimumVersion.ToString();
  499. }
  500. return new LocalPlugin(dir, _appVersion >= targetAbi && _appVersion <= maxAbi, manifest);
  501. }
  502. // No metafile, so lets see if the folder is versioned.
  503. // TODO: Phase this support out in future versions.
  504. metafile = dir.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries)[^1];
  505. int versionIndex = dir.LastIndexOf('_');
  506. if (versionIndex != -1)
  507. {
  508. // Get the version number from the filename if possible.
  509. metafile = Path.GetFileName(dir[..versionIndex]) ?? dir[..versionIndex];
  510. version = Version.TryParse(dir.AsSpan()[(versionIndex + 1)..], out Version? parsedVersion) ? parsedVersion : _appVersion;
  511. }
  512. else
  513. {
  514. // Un-versioned folder - Add it under the path name and version it suitable for this instance.
  515. version = _appVersion;
  516. }
  517. // Auto-create a plugin manifest, so we can disable it, if it fails to load.
  518. // NOTE: This Plugin is marked as valid for two upgrades, at which point, it can be assumed the
  519. // code base will have changed sufficiently to make it invalid.
  520. manifest = new PluginManifest
  521. {
  522. Status = PluginStatus.RestartRequired,
  523. Name = metafile,
  524. AutoUpdate = false,
  525. Guid = metafile.GetMD5(),
  526. TargetAbi = _appVersion.ToString(),
  527. MaxAbi = _nextVersion.ToString(),
  528. Version = version.ToString()
  529. };
  530. return new LocalPlugin(dir, true, manifest);
  531. }
  532. #pragma warning disable CA1031 // Do not catch general exception types
  533. catch (Exception ex)
  534. #pragma warning restore CA1031 // Do not catch general exception types
  535. {
  536. _logger.LogError(ex, "Something went wrong!");
  537. return null;
  538. }
  539. }
  540. /// <summary>
  541. /// Gets the list of local plugins.
  542. /// </summary>
  543. /// <returns>Enumerable of local plugins.</returns>
  544. private IEnumerable<LocalPlugin> DiscoverPlugins()
  545. {
  546. var versions = new List<LocalPlugin>();
  547. if (!Directory.Exists(_pluginsPath))
  548. {
  549. // Plugin path doesn't exist, don't try to enumerate sub-folders.
  550. return Enumerable.Empty<LocalPlugin>();
  551. }
  552. var directories = Directory.EnumerateDirectories(_pluginsPath, "*.*", SearchOption.TopDirectoryOnly);
  553. LocalPlugin? entry;
  554. foreach (var dir in directories)
  555. {
  556. entry = LoadManifest(dir);
  557. if (entry != null)
  558. {
  559. versions.Add(entry);
  560. }
  561. }
  562. string lastName = string.Empty;
  563. versions.Sort(LocalPlugin.Compare);
  564. // Traverse backwards through the list.
  565. // The first item will be the latest version.
  566. for (int x = versions.Count - 1; x >= 0; x--)
  567. {
  568. entry = versions[x];
  569. if (!string.Equals(lastName, entry.Name, StringComparison.OrdinalIgnoreCase))
  570. {
  571. entry.DllFiles.AddRange(Directory.EnumerateFiles(entry.Path, "*.dll", SearchOption.AllDirectories));
  572. if (entry.IsEnabledAndSupported)
  573. {
  574. lastName = entry.Name;
  575. continue;
  576. }
  577. }
  578. if (string.IsNullOrEmpty(lastName))
  579. {
  580. continue;
  581. }
  582. var manifest = entry.Manifest;
  583. var cleaned = false;
  584. var path = entry.Path;
  585. if (_config.RemoveOldPlugins)
  586. {
  587. // Attempt a cleanup of old folders.
  588. try
  589. {
  590. _logger.LogDebug("Deleting {Path}", path);
  591. Directory.Delete(path, true);
  592. cleaned = true;
  593. }
  594. #pragma warning disable CA1031 // Do not catch general exception types
  595. catch (Exception e)
  596. #pragma warning restore CA1031 // Do not catch general exception types
  597. {
  598. _logger.LogWarning(e, "Unable to delete {Path}", path);
  599. }
  600. versions.RemoveAt(x);
  601. }
  602. if (!cleaned)
  603. {
  604. if (manifest == null)
  605. {
  606. _logger.LogWarning("Unable to disable plugin {Path}", entry.Path);
  607. continue;
  608. }
  609. manifest.Status = PluginStatus.DeleteOnStartup;
  610. SaveManifest(manifest, entry.Path);
  611. }
  612. }
  613. // Only want plugin folders which have files.
  614. return versions.Where(p => p.DllFiles.Count != 0);
  615. }
  616. }
  617. }