PluginManager.cs 29 KB

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