PluginManager.cs 29 KB

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