PluginManager.cs 29 KB

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