ApplicationHost.cs 47 KB

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