2
0

PluginManager.cs 26 KB

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