ApplicationHost.cs 46 KB

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