PluginManager.cs 29 KB

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