ApplicationHost.cs 47 KB

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