ApplicationHost.cs 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Reflection;
  12. using System.Runtime.InteropServices;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using Emby.Dlna;
  17. using Emby.Dlna.Main;
  18. using Emby.Dlna.Ssdp;
  19. using Emby.Drawing;
  20. using Emby.Notifications;
  21. using Emby.Photos;
  22. using Emby.Server.Implementations.Archiving;
  23. using Emby.Server.Implementations.Channels;
  24. using Emby.Server.Implementations.Collections;
  25. using Emby.Server.Implementations.Configuration;
  26. using Emby.Server.Implementations.Cryptography;
  27. using Emby.Server.Implementations.Data;
  28. using Emby.Server.Implementations.Devices;
  29. using Emby.Server.Implementations.Dto;
  30. using Emby.Server.Implementations.HttpServer.Security;
  31. using Emby.Server.Implementations.IO;
  32. using Emby.Server.Implementations.Library;
  33. using Emby.Server.Implementations.LiveTv;
  34. using Emby.Server.Implementations.Localization;
  35. using Emby.Server.Implementations.Net;
  36. using Emby.Server.Implementations.Playlists;
  37. using Emby.Server.Implementations.Plugins;
  38. using Emby.Server.Implementations.QuickConnect;
  39. using Emby.Server.Implementations.ScheduledTasks;
  40. using Emby.Server.Implementations.Serialization;
  41. using Emby.Server.Implementations.Session;
  42. using Emby.Server.Implementations.SyncPlay;
  43. using Emby.Server.Implementations.TV;
  44. using Emby.Server.Implementations.Udp;
  45. using Emby.Server.Implementations.Updates;
  46. using Jellyfin.Api.Helpers;
  47. using Jellyfin.Networking.Configuration;
  48. using Jellyfin.Networking.Manager;
  49. using MediaBrowser.Common;
  50. using MediaBrowser.Common.Configuration;
  51. using MediaBrowser.Common.Events;
  52. using MediaBrowser.Common.Net;
  53. using MediaBrowser.Common.Plugins;
  54. using MediaBrowser.Common.Updates;
  55. using MediaBrowser.Controller;
  56. using MediaBrowser.Controller.Channels;
  57. using MediaBrowser.Controller.Chapters;
  58. using MediaBrowser.Controller.ClientEvent;
  59. using MediaBrowser.Controller.Collections;
  60. using MediaBrowser.Controller.Configuration;
  61. using MediaBrowser.Controller.Dlna;
  62. using MediaBrowser.Controller.Drawing;
  63. using MediaBrowser.Controller.Dto;
  64. using MediaBrowser.Controller.Entities;
  65. using MediaBrowser.Controller.Library;
  66. using MediaBrowser.Controller.LiveTv;
  67. using MediaBrowser.Controller.MediaEncoding;
  68. using MediaBrowser.Controller.Net;
  69. using MediaBrowser.Controller.Notifications;
  70. using MediaBrowser.Controller.Persistence;
  71. using MediaBrowser.Controller.Playlists;
  72. using MediaBrowser.Controller.Plugins;
  73. using MediaBrowser.Controller.Providers;
  74. using MediaBrowser.Controller.QuickConnect;
  75. using MediaBrowser.Controller.Resolvers;
  76. using MediaBrowser.Controller.Session;
  77. using MediaBrowser.Controller.Sorting;
  78. using MediaBrowser.Controller.Subtitles;
  79. using MediaBrowser.Controller.SyncPlay;
  80. using MediaBrowser.Controller.TV;
  81. using MediaBrowser.LocalMetadata.Savers;
  82. using MediaBrowser.MediaEncoding.BdInfo;
  83. using MediaBrowser.Model.Cryptography;
  84. using MediaBrowser.Model.Dlna;
  85. using MediaBrowser.Model.Globalization;
  86. using MediaBrowser.Model.IO;
  87. using MediaBrowser.Model.MediaInfo;
  88. using MediaBrowser.Model.Net;
  89. using MediaBrowser.Model.Serialization;
  90. using MediaBrowser.Model.System;
  91. using MediaBrowser.Model.Tasks;
  92. using MediaBrowser.Providers.Chapters;
  93. using MediaBrowser.Providers.Manager;
  94. using MediaBrowser.Providers.Plugins.Tmdb;
  95. using MediaBrowser.Providers.Subtitles;
  96. using MediaBrowser.XbmcMetadata.Providers;
  97. using Microsoft.AspNetCore.Http;
  98. using Microsoft.AspNetCore.Mvc;
  99. using Microsoft.Extensions.Configuration;
  100. using Microsoft.Extensions.DependencyInjection;
  101. using Microsoft.Extensions.Logging;
  102. using Prometheus.DotNetRuntime;
  103. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  104. namespace Emby.Server.Implementations
  105. {
  106. /// <summary>
  107. /// Class CompositionRoot.
  108. /// </summary>
  109. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  110. {
  111. /// <summary>
  112. /// The environment variable prefixes to log at server startup.
  113. /// </summary>
  114. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  115. /// <summary>
  116. /// The disposable parts.
  117. /// </summary>
  118. private readonly ConcurrentDictionary<IDisposable, byte> _disposableParts = new ();
  119. private readonly IFileSystem _fileSystemManager;
  120. private readonly IConfiguration _startupConfig;
  121. private readonly IXmlSerializer _xmlSerializer;
  122. private readonly IStartupOptions _startupOptions;
  123. private readonly IPluginManager _pluginManager;
  124. private List<Type> _creatingInstances;
  125. private IMediaEncoder _mediaEncoder;
  126. private ISessionManager _sessionManager;
  127. /// <summary>
  128. /// Gets or sets all concrete types.
  129. /// </summary>
  130. /// <value>All concrete types.</value>
  131. private Type[] _allConcreteTypes;
  132. private DeviceId _deviceId;
  133. private bool _disposed = false;
  134. /// <summary>
  135. /// Initializes a new instance of the <see cref="ApplicationHost"/> class.
  136. /// </summary>
  137. /// <param name="applicationPaths">Instance of the <see cref="IServerApplicationPaths"/> interface.</param>
  138. /// <param name="loggerFactory">Instance of the <see cref="ILoggerFactory"/> interface.</param>
  139. /// <param name="options">Instance of the <see cref="IStartupOptions"/> interface.</param>
  140. /// <param name="startupConfig">The <see cref="IConfiguration" /> interface.</param>
  141. public ApplicationHost(
  142. IServerApplicationPaths applicationPaths,
  143. ILoggerFactory loggerFactory,
  144. IStartupOptions options,
  145. IConfiguration startupConfig)
  146. {
  147. ApplicationPaths = applicationPaths;
  148. LoggerFactory = loggerFactory;
  149. _startupOptions = options;
  150. _startupConfig = startupConfig;
  151. _fileSystemManager = new ManagedFileSystem(LoggerFactory.CreateLogger<ManagedFileSystem>(), applicationPaths);
  152. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  153. _fileSystemManager.AddShortcutHandler(new MbLinkShortcutHandler(_fileSystemManager));
  154. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  155. ApplicationVersionString = ApplicationVersion.ToString(3);
  156. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  157. _xmlSerializer = new MyXmlSerializer();
  158. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  159. _pluginManager = new PluginManager(
  160. LoggerFactory.CreateLogger<PluginManager>(),
  161. this,
  162. ConfigurationManager.Configuration,
  163. ApplicationPaths.PluginsPath,
  164. ApplicationVersion);
  165. }
  166. /// <summary>
  167. /// Occurs when [has pending restart changed].
  168. /// </summary>
  169. public event EventHandler HasPendingRestartChanged;
  170. /// <summary>
  171. /// Gets a value indicating whether this instance can self restart.
  172. /// </summary>
  173. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  174. public bool CoreStartupHasCompleted { get; private set; }
  175. public virtual bool CanLaunchWebBrowser
  176. {
  177. get
  178. {
  179. if (!Environment.UserInteractive)
  180. {
  181. return false;
  182. }
  183. if (_startupOptions.IsService)
  184. {
  185. return false;
  186. }
  187. return OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
  188. }
  189. }
  190. /// <summary>
  191. /// Gets the <see cref="INetworkManager"/> singleton instance.
  192. /// </summary>
  193. public INetworkManager NetManager { get; private set; }
  194. /// <summary>
  195. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  196. /// </summary>
  197. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  198. public bool HasPendingRestart { get; private set; }
  199. /// <inheritdoc />
  200. public bool IsShuttingDown { get; private set; }
  201. /// <summary>
  202. /// Gets the logger.
  203. /// </summary>
  204. protected ILogger<ApplicationHost> Logger { get; }
  205. /// <summary>
  206. /// Gets the logger factory.
  207. /// </summary>
  208. protected ILoggerFactory LoggerFactory { get; }
  209. /// <summary>
  210. /// Gets the application paths.
  211. /// </summary>
  212. /// <value>The application paths.</value>
  213. protected IServerApplicationPaths ApplicationPaths { get; }
  214. /// <summary>
  215. /// Gets the configuration manager.
  216. /// </summary>
  217. /// <value>The configuration manager.</value>
  218. public ServerConfigurationManager ConfigurationManager { get; }
  219. /// <summary>
  220. /// Gets or sets the service provider.
  221. /// </summary>
  222. public IServiceProvider ServiceProvider { get; set; }
  223. /// <summary>
  224. /// Gets the http port for the webhost.
  225. /// </summary>
  226. public int HttpPort { get; private set; }
  227. /// <summary>
  228. /// Gets the https port for the webhost.
  229. /// </summary>
  230. public int HttpsPort { get; private set; }
  231. /// <summary>
  232. /// Gets the value of the PublishedServerUrl setting.
  233. /// </summary>
  234. public string PublishedServerUrl => _startupOptions.PublishedServerUrl ?? _startupConfig[UdpServer.AddressOverrideConfigKey];
  235. /// <inheritdoc />
  236. public Version ApplicationVersion { get; }
  237. /// <inheritdoc />
  238. public string ApplicationVersionString { get; }
  239. /// <summary>
  240. /// Gets the current application user agent.
  241. /// </summary>
  242. /// <value>The application user agent.</value>
  243. public string ApplicationUserAgent { get; }
  244. /// <summary>
  245. /// Gets the email address for use within a comment section of a user agent field.
  246. /// Presently used to provide contact information to MusicBrainz service.
  247. /// </summary>
  248. public string ApplicationUserAgentAddress => "team@jellyfin.org";
  249. /// <summary>
  250. /// Gets the current application name.
  251. /// </summary>
  252. /// <value>The application name.</value>
  253. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  254. public string SystemId
  255. {
  256. get
  257. {
  258. _deviceId ??= new DeviceId(ApplicationPaths, LoggerFactory);
  259. return _deviceId.Value;
  260. }
  261. }
  262. /// <inheritdoc/>
  263. public string Name => ApplicationProductName;
  264. private string CertificatePath { get; set; }
  265. public X509Certificate2 Certificate { get; private set; }
  266. /// <inheritdoc/>
  267. public bool ListenWithHttps => Certificate != null && ConfigurationManager.GetNetworkConfiguration().EnableHttps;
  268. public string FriendlyName =>
  269. string.IsNullOrEmpty(ConfigurationManager.Configuration.ServerName)
  270. ? Environment.MachineName
  271. : ConfigurationManager.Configuration.ServerName;
  272. /// <summary>
  273. /// Temporary function to migration network settings out of system.xml and into network.xml.
  274. /// TODO: remove at the point when a fixed migration path has been decided upon.
  275. /// </summary>
  276. private void MigrateNetworkConfiguration()
  277. {
  278. string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
  279. if (!File.Exists(path))
  280. {
  281. var networkSettings = new NetworkConfiguration();
  282. ClassMigrationHelper.CopyProperties(ConfigurationManager.Configuration, networkSettings);
  283. _xmlSerializer.SerializeToFile(networkSettings, path);
  284. Logger.LogDebug("Successfully migrated network settings.");
  285. }
  286. }
  287. public string ExpandVirtualPath(string path)
  288. {
  289. var appPaths = ApplicationPaths;
  290. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  291. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  292. }
  293. public string ReverseVirtualPath(string path)
  294. {
  295. var appPaths = ApplicationPaths;
  296. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  297. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  298. }
  299. /// <summary>
  300. /// Creates the instance safe.
  301. /// </summary>
  302. /// <param name="type">The type.</param>
  303. /// <returns>System.Object.</returns>
  304. protected object CreateInstanceSafe(Type type)
  305. {
  306. _creatingInstances ??= new List<Type>();
  307. if (_creatingInstances.Contains(type))
  308. {
  309. Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
  310. foreach (var entry in _creatingInstances)
  311. {
  312. Logger.LogError("Called from: {TypeName}", entry.FullName);
  313. }
  314. _pluginManager.FailPlugin(type.Assembly);
  315. throw new TypeLoadException("DI Loop detected");
  316. }
  317. try
  318. {
  319. _creatingInstances.Add(type);
  320. Logger.LogDebug("Creating instance of {Type}", type);
  321. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  322. }
  323. catch (Exception ex)
  324. {
  325. Logger.LogError(ex, "Error creating {Type}", type);
  326. // If this is a plugin fail it.
  327. _pluginManager.FailPlugin(type.Assembly);
  328. return null;
  329. }
  330. finally
  331. {
  332. _creatingInstances.Remove(type);
  333. }
  334. }
  335. /// <summary>
  336. /// Resolves this instance.
  337. /// </summary>
  338. /// <typeparam name="T">The type.</typeparam>
  339. /// <returns>``0.</returns>
  340. public T Resolve<T>() => ServiceProvider.GetService<T>();
  341. /// <inheritdoc/>
  342. public IEnumerable<Type> GetExportTypes<T>()
  343. {
  344. var currentType = typeof(T);
  345. var numberOfConcreteTypes = _allConcreteTypes.Length;
  346. for (var i = 0; i < numberOfConcreteTypes; i++)
  347. {
  348. var type = _allConcreteTypes[i];
  349. if (currentType.IsAssignableFrom(type))
  350. {
  351. yield return type;
  352. }
  353. }
  354. }
  355. /// <inheritdoc />
  356. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  357. {
  358. // Convert to list so this isn't executed for each iteration
  359. var parts = GetExportTypes<T>()
  360. .Select(CreateInstanceSafe)
  361. .Where(i => i != null)
  362. .Cast<T>()
  363. .ToList();
  364. if (manageLifetime)
  365. {
  366. foreach (var part in parts.OfType<IDisposable>())
  367. {
  368. _disposableParts.TryAdd(part, byte.MinValue);
  369. }
  370. }
  371. return parts;
  372. }
  373. /// <inheritdoc />
  374. public IReadOnlyCollection<T> GetExports<T>(CreationDelegateFactory defaultFunc, bool manageLifetime = true)
  375. {
  376. // Convert to list so this isn't executed for each iteration
  377. var parts = GetExportTypes<T>()
  378. .Select(i => defaultFunc(i))
  379. .Where(i => i != null)
  380. .Cast<T>()
  381. .ToList();
  382. if (manageLifetime)
  383. {
  384. foreach (var part in parts.OfType<IDisposable>())
  385. {
  386. _disposableParts.TryAdd(part, byte.MinValue);
  387. }
  388. }
  389. return parts;
  390. }
  391. /// <summary>
  392. /// Runs the startup tasks.
  393. /// </summary>
  394. /// <param name="cancellationToken">The cancellation token.</param>
  395. /// <returns><see cref="Task" />.</returns>
  396. public async Task RunStartupTasksAsync(CancellationToken cancellationToken)
  397. {
  398. cancellationToken.ThrowIfCancellationRequested();
  399. Logger.LogInformation("Running startup tasks");
  400. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  401. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  402. ConfigurationManager.NamedConfigurationUpdated += OnConfigurationUpdated;
  403. _mediaEncoder.SetFFmpegPath();
  404. Logger.LogInformation("ServerId: {ServerId}", SystemId);
  405. var entryPoints = GetExports<IServerEntryPoint>();
  406. cancellationToken.ThrowIfCancellationRequested();
  407. var stopWatch = new Stopwatch();
  408. stopWatch.Start();
  409. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  410. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  411. Logger.LogInformation("Core startup complete");
  412. CoreStartupHasCompleted = true;
  413. cancellationToken.ThrowIfCancellationRequested();
  414. stopWatch.Restart();
  415. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  416. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  417. stopWatch.Stop();
  418. }
  419. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  420. {
  421. foreach (var entryPoint in entryPoints)
  422. {
  423. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  424. {
  425. continue;
  426. }
  427. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  428. yield return entryPoint.RunAsync();
  429. }
  430. }
  431. /// <inheritdoc/>
  432. public void Init(IServiceCollection serviceCollection)
  433. {
  434. DiscoverTypes();
  435. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  436. // Have to migrate settings here as migration subsystem not yet initialised.
  437. MigrateNetworkConfiguration();
  438. NetManager = new NetworkManager(ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
  439. // Initialize runtime stat collection
  440. if (ConfigurationManager.Configuration.EnableMetrics)
  441. {
  442. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  443. }
  444. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  445. HttpPort = networkConfiguration.HttpServerPortNumber;
  446. HttpsPort = networkConfiguration.HttpsPortNumber;
  447. // Safeguard against invalid configuration
  448. if (HttpPort == HttpsPort)
  449. {
  450. HttpPort = NetworkConfiguration.DefaultHttpPort;
  451. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  452. }
  453. CertificatePath = networkConfiguration.CertificatePath;
  454. Certificate = GetCertificate(CertificatePath, networkConfiguration.CertificatePassword);
  455. RegisterServices(serviceCollection);
  456. _pluginManager.RegisterServices(serviceCollection);
  457. }
  458. /// <summary>
  459. /// Registers services/resources with the service collection that will be available via DI.
  460. /// </summary>
  461. /// <param name="serviceCollection">Instance of the <see cref="IServiceCollection"/> interface.</param>
  462. protected virtual void RegisterServices(IServiceCollection serviceCollection)
  463. {
  464. serviceCollection.AddSingleton(_startupOptions);
  465. serviceCollection.AddMemoryCache();
  466. serviceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  467. serviceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  468. serviceCollection.AddSingleton<IApplicationHost>(this);
  469. serviceCollection.AddSingleton(_pluginManager);
  470. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  471. serviceCollection.AddSingleton(_fileSystemManager);
  472. serviceCollection.AddSingleton<TmdbClientManager>();
  473. serviceCollection.AddSingleton(NetManager);
  474. serviceCollection.AddSingleton<ITaskManager, TaskManager>();
  475. serviceCollection.AddSingleton(_xmlSerializer);
  476. serviceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  477. serviceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  478. serviceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  479. serviceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  480. serviceCollection.AddSingleton<IZipClient, ZipClient>();
  481. serviceCollection.AddSingleton<IServerApplicationHost>(this);
  482. serviceCollection.AddSingleton(ApplicationPaths);
  483. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  484. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  485. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  486. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  487. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  488. serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  489. serviceCollection.AddSingleton<EncodingHelper>();
  490. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  491. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  492. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  493. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  494. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  495. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  496. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  497. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  498. serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  499. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  500. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  501. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  502. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  503. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  504. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  505. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  506. serviceCollection.AddSingleton<IDtoService, DtoService>();
  507. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  508. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  509. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  510. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  511. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  512. serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  513. serviceCollection.AddSingleton<LiveTvDtoService>();
  514. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  515. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  516. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  517. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  518. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  519. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  520. serviceCollection.AddScoped<ISessionContext, SessionContext>();
  521. serviceCollection.AddSingleton<IAuthService, AuthService>();
  522. serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  523. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  524. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  525. serviceCollection.AddSingleton<TranscodingJobHelper>();
  526. serviceCollection.AddScoped<MediaInfoHelper>();
  527. serviceCollection.AddScoped<AudioHelper>();
  528. serviceCollection.AddScoped<DynamicHlsHelper>();
  529. serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
  530. serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  531. }
  532. /// <summary>
  533. /// Create services registered with the service container that need to be initialized at application startup.
  534. /// </summary>
  535. /// <returns>A task representing the service initialization operation.</returns>
  536. public async Task InitializeServices()
  537. {
  538. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  539. await localizationManager.LoadAll().ConfigureAwait(false);
  540. _mediaEncoder = Resolve<IMediaEncoder>();
  541. _sessionManager = Resolve<ISessionManager>();
  542. SetStaticProperties();
  543. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  544. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  545. FindParts();
  546. }
  547. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  548. {
  549. // Distinct these to prevent users from reporting problems that aren't actually problems
  550. var commandLineArgs = Environment
  551. .GetCommandLineArgs()
  552. .Distinct();
  553. // Get all relevant environment variables
  554. var allEnvVars = Environment.GetEnvironmentVariables();
  555. var relevantEnvVars = new Dictionary<object, object>();
  556. foreach (var key in allEnvVars.Keys)
  557. {
  558. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  559. {
  560. relevantEnvVars.Add(key, allEnvVars[key]);
  561. }
  562. }
  563. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  564. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  565. logger.LogInformation("Operating system: {OS}", MediaBrowser.Common.System.OperatingSystem.Name);
  566. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  567. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  568. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  569. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  570. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  571. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  572. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  573. }
  574. private X509Certificate2 GetCertificate(string path, string password)
  575. {
  576. if (string.IsNullOrWhiteSpace(path))
  577. {
  578. return null;
  579. }
  580. try
  581. {
  582. if (!File.Exists(path))
  583. {
  584. return null;
  585. }
  586. // Don't use an empty string password
  587. password = string.IsNullOrWhiteSpace(password) ? null : password;
  588. var localCert = new X509Certificate2(path, password, X509KeyStorageFlags.UserKeySet);
  589. if (!localCert.HasPrivateKey)
  590. {
  591. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
  592. return null;
  593. }
  594. return localCert;
  595. }
  596. catch (Exception ex)
  597. {
  598. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
  599. return null;
  600. }
  601. }
  602. /// <summary>
  603. /// Dirty hacks.
  604. /// </summary>
  605. private void SetStaticProperties()
  606. {
  607. // For now there's no real way to inject these properly
  608. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  609. BaseItem.ConfigurationManager = ConfigurationManager;
  610. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  611. BaseItem.ProviderManager = Resolve<IProviderManager>();
  612. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  613. BaseItem.ItemRepository = Resolve<IItemRepository>();
  614. BaseItem.FileSystem = _fileSystemManager;
  615. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  616. BaseItem.ChannelManager = Resolve<IChannelManager>();
  617. Video.LiveTvManager = Resolve<ILiveTvManager>();
  618. Folder.UserViewManager = Resolve<IUserViewManager>();
  619. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  620. UserView.CollectionManager = Resolve<ICollectionManager>();
  621. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  622. CollectionFolder.XmlSerializer = _xmlSerializer;
  623. CollectionFolder.ApplicationHost = this;
  624. }
  625. /// <summary>
  626. /// Finds plugin components and register them with the appropriate services.
  627. /// </summary>
  628. private void FindParts()
  629. {
  630. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  631. {
  632. ConfigurationManager.Configuration.IsPortAuthorized = true;
  633. ConfigurationManager.SaveConfiguration();
  634. }
  635. _pluginManager.CreatePlugins();
  636. Resolve<ILibraryManager>().AddParts(
  637. GetExports<IResolverIgnoreRule>(),
  638. GetExports<IItemResolver>(),
  639. GetExports<IIntroProvider>(),
  640. GetExports<IBaseItemComparer>(),
  641. GetExports<ILibraryPostScanTask>());
  642. Resolve<IProviderManager>().AddParts(
  643. GetExports<IImageProvider>(),
  644. GetExports<IMetadataService>(),
  645. GetExports<IMetadataProvider>(),
  646. GetExports<IMetadataSaver>(),
  647. GetExports<IExternalId>());
  648. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  649. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  650. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  651. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  652. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  653. }
  654. /// <summary>
  655. /// Discovers the types.
  656. /// </summary>
  657. protected void DiscoverTypes()
  658. {
  659. Logger.LogInformation("Loading assemblies");
  660. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  661. }
  662. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  663. {
  664. foreach (var ass in assemblies)
  665. {
  666. Type[] exportedTypes;
  667. try
  668. {
  669. exportedTypes = ass.GetExportedTypes();
  670. }
  671. catch (FileNotFoundException ex)
  672. {
  673. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  674. _pluginManager.FailPlugin(ass);
  675. continue;
  676. }
  677. catch (TypeLoadException ex)
  678. {
  679. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  680. _pluginManager.FailPlugin(ass);
  681. continue;
  682. }
  683. foreach (Type type in exportedTypes)
  684. {
  685. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  686. {
  687. yield return type;
  688. }
  689. }
  690. }
  691. }
  692. /// <summary>
  693. /// Called when [configuration updated].
  694. /// </summary>
  695. /// <param name="sender">The sender.</param>
  696. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  697. private void OnConfigurationUpdated(object sender, EventArgs e)
  698. {
  699. var requiresRestart = false;
  700. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  701. // Don't do anything if these haven't been set yet
  702. if (HttpPort != 0 && HttpsPort != 0)
  703. {
  704. // Need to restart if ports have changed
  705. if (networkConfiguration.HttpServerPortNumber != HttpPort
  706. || networkConfiguration.HttpsPortNumber != HttpsPort)
  707. {
  708. if (ConfigurationManager.Configuration.IsPortAuthorized)
  709. {
  710. ConfigurationManager.Configuration.IsPortAuthorized = false;
  711. ConfigurationManager.SaveConfiguration();
  712. requiresRestart = true;
  713. }
  714. }
  715. }
  716. if (ValidateSslCertificate(networkConfiguration))
  717. {
  718. requiresRestart = true;
  719. }
  720. if (requiresRestart)
  721. {
  722. Logger.LogInformation("App needs to be restarted due to configuration change.");
  723. NotifyPendingRestart();
  724. }
  725. }
  726. /// <summary>
  727. /// Validates the SSL certificate.
  728. /// </summary>
  729. /// <param name="networkConfig">The new configuration.</param>
  730. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  731. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  732. {
  733. var newPath = networkConfig.CertificatePath;
  734. if (!string.IsNullOrWhiteSpace(newPath)
  735. && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
  736. {
  737. if (File.Exists(newPath))
  738. {
  739. return true;
  740. }
  741. throw new FileNotFoundException(
  742. string.Format(
  743. CultureInfo.InvariantCulture,
  744. "Certificate file '{0}' does not exist.",
  745. newPath));
  746. }
  747. return false;
  748. }
  749. /// <summary>
  750. /// Notifies the kernel that a change has been made that requires a restart.
  751. /// </summary>
  752. public void NotifyPendingRestart()
  753. {
  754. Logger.LogInformation("App needs to be restarted.");
  755. var changed = !HasPendingRestart;
  756. HasPendingRestart = true;
  757. if (changed)
  758. {
  759. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  760. }
  761. }
  762. /// <summary>
  763. /// Restarts this instance.
  764. /// </summary>
  765. public void Restart()
  766. {
  767. if (!CanSelfRestart)
  768. {
  769. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  770. }
  771. if (IsShuttingDown)
  772. {
  773. return;
  774. }
  775. IsShuttingDown = true;
  776. Task.Run(async () =>
  777. {
  778. try
  779. {
  780. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  781. }
  782. catch (Exception ex)
  783. {
  784. Logger.LogError(ex, "Error sending server restart notification");
  785. }
  786. Logger.LogInformation("Calling RestartInternal");
  787. RestartInternal();
  788. });
  789. }
  790. protected abstract void RestartInternal();
  791. /// <summary>
  792. /// Gets the composable part assemblies.
  793. /// </summary>
  794. /// <returns>IEnumerable{Assembly}.</returns>
  795. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  796. {
  797. foreach (var p in _pluginManager.LoadAssemblies())
  798. {
  799. yield return p;
  800. }
  801. // Include composable parts in the Model assembly
  802. yield return typeof(SystemInfo).Assembly;
  803. // Include composable parts in the Common assembly
  804. yield return typeof(IApplicationHost).Assembly;
  805. // Include composable parts in the Controller assembly
  806. yield return typeof(IServerApplicationHost).Assembly;
  807. // Include composable parts in the Providers assembly
  808. yield return typeof(ProviderUtils).Assembly;
  809. // Include composable parts in the Photos assembly
  810. yield return typeof(PhotoProvider).Assembly;
  811. // Emby.Server implementations
  812. yield return typeof(InstallationManager).Assembly;
  813. // MediaEncoding
  814. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  815. // Dlna
  816. yield return typeof(DlnaEntryPoint).Assembly;
  817. // Local metadata
  818. yield return typeof(BoxSetXmlSaver).Assembly;
  819. // Notifications
  820. yield return typeof(NotificationManager).Assembly;
  821. // Xbmc
  822. yield return typeof(ArtistNfoProvider).Assembly;
  823. // Network
  824. yield return typeof(NetworkManager).Assembly;
  825. foreach (var i in GetAssembliesWithPartsInternal())
  826. {
  827. yield return i;
  828. }
  829. }
  830. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  831. /// <summary>
  832. /// Gets the system status.
  833. /// </summary>
  834. /// <param name="request">Where this request originated.</param>
  835. /// <returns>SystemInfo.</returns>
  836. public SystemInfo GetSystemInfo(HttpRequest request)
  837. {
  838. return new SystemInfo
  839. {
  840. HasPendingRestart = HasPendingRestart,
  841. IsShuttingDown = IsShuttingDown,
  842. Version = ApplicationVersionString,
  843. WebSocketPortNumber = HttpPort,
  844. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  845. Id = SystemId,
  846. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  847. WebPath = ApplicationPaths.WebPath,
  848. LogPath = ApplicationPaths.LogDirectoryPath,
  849. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  850. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  851. CachePath = ApplicationPaths.CachePath,
  852. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  853. OperatingSystemDisplayName = MediaBrowser.Common.System.OperatingSystem.Name,
  854. CanSelfRestart = CanSelfRestart,
  855. CanLaunchWebBrowser = CanLaunchWebBrowser,
  856. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  857. ServerName = FriendlyName,
  858. LocalAddress = GetSmartApiUrl(request),
  859. SupportsLibraryMonitor = true,
  860. SystemArchitecture = RuntimeInformation.OSArchitecture,
  861. PackageName = _startupOptions.PackageName
  862. };
  863. }
  864. public PublicSystemInfo GetPublicSystemInfo(HttpRequest request)
  865. {
  866. return new PublicSystemInfo
  867. {
  868. Version = ApplicationVersionString,
  869. ProductName = ApplicationProductName,
  870. Id = SystemId,
  871. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  872. ServerName = FriendlyName,
  873. LocalAddress = GetSmartApiUrl(request),
  874. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  875. };
  876. }
  877. /// <inheritdoc/>
  878. public string GetSmartApiUrl(IPAddress remoteAddr)
  879. {
  880. // Published server ends with a /
  881. if (!string.IsNullOrEmpty(PublishedServerUrl))
  882. {
  883. // Published server ends with a '/', so we need to remove it.
  884. return PublishedServerUrl.Trim('/');
  885. }
  886. string smart = NetManager.GetBindInterface(remoteAddr, out var port);
  887. return GetLocalApiUrl(smart.Trim('/'), null, port);
  888. }
  889. /// <inheritdoc/>
  890. public string GetSmartApiUrl(HttpRequest request)
  891. {
  892. // Return the host in the HTTP request as the API url
  893. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  894. {
  895. int? requestPort = request.Host.Port;
  896. if ((requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  897. {
  898. requestPort = -1;
  899. }
  900. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  901. }
  902. // Published server ends with a /
  903. if (!string.IsNullOrEmpty(PublishedServerUrl))
  904. {
  905. // Published server ends with a '/', so we need to remove it.
  906. return PublishedServerUrl.Trim('/');
  907. }
  908. string smart = NetManager.GetBindInterface(request, out var port);
  909. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  910. }
  911. /// <inheritdoc/>
  912. public string GetSmartApiUrl(string hostname)
  913. {
  914. // Published server ends with a /
  915. if (!string.IsNullOrEmpty(PublishedServerUrl))
  916. {
  917. // Published server ends with a '/', so we need to remove it.
  918. return PublishedServerUrl.Trim('/');
  919. }
  920. string smart = NetManager.GetBindInterface(hostname, out var port);
  921. return GetLocalApiUrl(smart.Trim('/'), null, port);
  922. }
  923. /// <inheritdoc/>
  924. public string GetApiUrlForLocalAccess(bool allowHttps)
  925. {
  926. // With an empty source, the port will be null
  927. string smart = NetManager.GetBindInterface(string.Empty, out _);
  928. var scheme = allowHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  929. var port = allowHttps ? HttpsPort : HttpPort;
  930. return GetLocalApiUrl(smart.Trim('/'), scheme, port);
  931. }
  932. /// <inheritdoc/>
  933. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  934. {
  935. // If the smartAPI doesn't start with http then treat it as a host or ip.
  936. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  937. {
  938. return hostname.TrimEnd('/');
  939. }
  940. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  941. // not. For consistency, always trim the trailing slash.
  942. return new UriBuilder
  943. {
  944. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  945. Host = hostname,
  946. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  947. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  948. }.ToString().TrimEnd('/');
  949. }
  950. /// <inheritdoc />
  951. public async Task Shutdown()
  952. {
  953. if (IsShuttingDown)
  954. {
  955. return;
  956. }
  957. IsShuttingDown = true;
  958. try
  959. {
  960. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  961. }
  962. catch (Exception ex)
  963. {
  964. Logger.LogError(ex, "Error sending server shutdown notification");
  965. }
  966. ShutdownInternal();
  967. }
  968. protected abstract void ShutdownInternal();
  969. public IEnumerable<Assembly> GetApiPluginAssemblies()
  970. {
  971. var assemblies = _allConcreteTypes
  972. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  973. .Select(i => i.Assembly)
  974. .Distinct();
  975. foreach (var assembly in assemblies)
  976. {
  977. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  978. yield return assembly;
  979. }
  980. }
  981. /// <inheritdoc />
  982. public void Dispose()
  983. {
  984. Dispose(true);
  985. GC.SuppressFinalize(this);
  986. }
  987. /// <summary>
  988. /// Releases unmanaged and - optionally - managed resources.
  989. /// </summary>
  990. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  991. protected virtual void Dispose(bool dispose)
  992. {
  993. if (_disposed)
  994. {
  995. return;
  996. }
  997. if (dispose)
  998. {
  999. var type = GetType();
  1000. Logger.LogInformation("Disposing {Type}", type.Name);
  1001. foreach (var (part, _) in _disposableParts)
  1002. {
  1003. var partType = part.GetType();
  1004. if (partType == type)
  1005. {
  1006. continue;
  1007. }
  1008. Logger.LogInformation("Disposing {Type}", partType.Name);
  1009. try
  1010. {
  1011. part.Dispose();
  1012. }
  1013. catch (Exception ex)
  1014. {
  1015. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  1016. }
  1017. }
  1018. _disposableParts.Clear();
  1019. }
  1020. _disposed = true;
  1021. }
  1022. }
  1023. }