PluginManager.cs 27 KB

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