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