PluginManager.cs 29 KB

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