PluginManager.cs 28 KB

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