ApplicationHost.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  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.MediaEncoding;
  68. using MediaBrowser.Controller.Net;
  69. using MediaBrowser.Controller.Notifications;
  70. using MediaBrowser.Controller.Persistence;
  71. using MediaBrowser.Controller.Playlists;
  72. using MediaBrowser.Controller.Plugins;
  73. using MediaBrowser.Controller.Providers;
  74. using MediaBrowser.Controller.QuickConnect;
  75. using MediaBrowser.Controller.Resolvers;
  76. using MediaBrowser.Controller.Session;
  77. using MediaBrowser.Controller.Sorting;
  78. using MediaBrowser.Controller.Subtitles;
  79. using MediaBrowser.Controller.SyncPlay;
  80. using MediaBrowser.Controller.TV;
  81. using MediaBrowser.LocalMetadata.Savers;
  82. using MediaBrowser.MediaEncoding.BdInfo;
  83. using MediaBrowser.Model.Cryptography;
  84. using MediaBrowser.Model.Dlna;
  85. using MediaBrowser.Model.Globalization;
  86. using MediaBrowser.Model.IO;
  87. using MediaBrowser.Model.MediaInfo;
  88. using MediaBrowser.Model.Net;
  89. using MediaBrowser.Model.Serialization;
  90. using MediaBrowser.Model.System;
  91. using MediaBrowser.Model.Tasks;
  92. using MediaBrowser.Providers.Chapters;
  93. using MediaBrowser.Providers.Manager;
  94. using MediaBrowser.Providers.Plugins.Tmdb;
  95. using MediaBrowser.Providers.Subtitles;
  96. using MediaBrowser.XbmcMetadata.Providers;
  97. using Microsoft.AspNetCore.Http;
  98. using Microsoft.AspNetCore.Mvc;
  99. using Microsoft.Extensions.Configuration;
  100. using Microsoft.Extensions.DependencyInjection;
  101. using Microsoft.Extensions.Logging;
  102. using Prometheus.DotNetRuntime;
  103. using static MediaBrowser.Controller.Extensions.ConfigurationExtensions;
  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. protected 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 the value of the PublishedServerUrl setting.
  173. /// </summary>
  174. private string PublishedServerUrl => _startupConfig[AddressOverrideKey];
  175. /// <summary>
  176. /// Gets a value indicating whether this instance can self restart.
  177. /// </summary>
  178. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  179. public bool CoreStartupHasCompleted { get; private set; }
  180. public virtual bool CanLaunchWebBrowser
  181. {
  182. get
  183. {
  184. if (!Environment.UserInteractive)
  185. {
  186. return false;
  187. }
  188. if (_startupOptions.IsService)
  189. {
  190. return false;
  191. }
  192. return OperatingSystem.IsWindows() || OperatingSystem.IsMacOS();
  193. }
  194. }
  195. /// <summary>
  196. /// Gets the <see cref="INetworkManager"/> singleton instance.
  197. /// </summary>
  198. public INetworkManager NetManager { get; private set; }
  199. /// <summary>
  200. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  201. /// </summary>
  202. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  203. public bool HasPendingRestart { get; private set; }
  204. /// <inheritdoc />
  205. public bool IsShuttingDown { get; private set; }
  206. /// <summary>
  207. /// Gets the logger.
  208. /// </summary>
  209. protected ILogger<ApplicationHost> Logger { get; }
  210. /// <summary>
  211. /// Gets the logger factory.
  212. /// </summary>
  213. protected ILoggerFactory LoggerFactory { get; }
  214. /// <summary>
  215. /// Gets the application paths.
  216. /// </summary>
  217. /// <value>The application paths.</value>
  218. protected IServerApplicationPaths ApplicationPaths { get; }
  219. /// <summary>
  220. /// Gets the configuration manager.
  221. /// </summary>
  222. /// <value>The configuration manager.</value>
  223. public ServerConfigurationManager ConfigurationManager { get; }
  224. /// <summary>
  225. /// Gets or sets the service provider.
  226. /// </summary>
  227. public IServiceProvider ServiceProvider { get; set; }
  228. /// <summary>
  229. /// Gets the http port for the webhost.
  230. /// </summary>
  231. public int HttpPort { get; private set; }
  232. /// <summary>
  233. /// Gets the https port for the webhost.
  234. /// </summary>
  235. public int HttpsPort { get; private set; }
  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<IServerApplicationHost>(this);
  465. serviceCollection.AddSingleton(ApplicationPaths);
  466. serviceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  467. serviceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  468. serviceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  469. serviceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  470. serviceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  471. serviceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  472. serviceCollection.AddSingleton<EncodingHelper>();
  473. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  474. serviceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  475. serviceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  476. serviceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  477. serviceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  478. serviceCollection.AddSingleton<NamingOptions>();
  479. serviceCollection.AddSingleton<IMusicManager, MusicManager>();
  480. serviceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  481. serviceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  482. serviceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  483. serviceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  484. serviceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  485. serviceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  486. serviceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  487. serviceCollection.AddSingleton<IProviderManager, ProviderManager>();
  488. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  489. serviceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  490. serviceCollection.AddSingleton<IDtoService, DtoService>();
  491. serviceCollection.AddSingleton<IChannelManager, ChannelManager>();
  492. serviceCollection.AddSingleton<ISessionManager, SessionManager>();
  493. serviceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  494. serviceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  495. serviceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  496. serviceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  497. serviceCollection.AddSingleton<LiveTvDtoService>();
  498. serviceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  499. serviceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  500. serviceCollection.AddSingleton<INotificationManager, NotificationManager>();
  501. serviceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  502. serviceCollection.AddSingleton<IChapterManager, ChapterManager>();
  503. serviceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  504. serviceCollection.AddScoped<ISessionContext, SessionContext>();
  505. serviceCollection.AddSingleton<IAuthService, AuthService>();
  506. serviceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  507. serviceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  508. serviceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  509. serviceCollection.AddSingleton<TranscodingJobHelper>();
  510. serviceCollection.AddScoped<MediaInfoHelper>();
  511. serviceCollection.AddScoped<AudioHelper>();
  512. serviceCollection.AddScoped<DynamicHlsHelper>();
  513. serviceCollection.AddScoped<IClientEventLogger, ClientEventLogger>();
  514. serviceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  515. }
  516. /// <summary>
  517. /// Create services registered with the service container that need to be initialized at application startup.
  518. /// </summary>
  519. /// <returns>A task representing the service initialization operation.</returns>
  520. public async Task InitializeServices()
  521. {
  522. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  523. await localizationManager.LoadAll().ConfigureAwait(false);
  524. _mediaEncoder = Resolve<IMediaEncoder>();
  525. _sessionManager = Resolve<ISessionManager>();
  526. SetStaticProperties();
  527. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  528. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  529. FindParts();
  530. }
  531. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  532. {
  533. // Distinct these to prevent users from reporting problems that aren't actually problems
  534. var commandLineArgs = Environment
  535. .GetCommandLineArgs()
  536. .Distinct();
  537. // Get all relevant environment variables
  538. var allEnvVars = Environment.GetEnvironmentVariables();
  539. var relevantEnvVars = new Dictionary<object, object>();
  540. foreach (var key in allEnvVars.Keys)
  541. {
  542. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  543. {
  544. relevantEnvVars.Add(key, allEnvVars[key]);
  545. }
  546. }
  547. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  548. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  549. logger.LogInformation("Operating system: {OS}", MediaBrowser.Common.System.OperatingSystem.Name);
  550. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  551. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  552. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  553. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  554. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  555. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  556. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  557. }
  558. private X509Certificate2 GetCertificate(string path, string password)
  559. {
  560. if (string.IsNullOrWhiteSpace(path))
  561. {
  562. return null;
  563. }
  564. try
  565. {
  566. if (!File.Exists(path))
  567. {
  568. return null;
  569. }
  570. // Don't use an empty string password
  571. password = string.IsNullOrWhiteSpace(password) ? null : password;
  572. var localCert = new X509Certificate2(path, password, X509KeyStorageFlags.UserKeySet);
  573. if (!localCert.HasPrivateKey)
  574. {
  575. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", path);
  576. return null;
  577. }
  578. return localCert;
  579. }
  580. catch (Exception ex)
  581. {
  582. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", path);
  583. return null;
  584. }
  585. }
  586. /// <summary>
  587. /// Dirty hacks.
  588. /// </summary>
  589. private void SetStaticProperties()
  590. {
  591. // For now there's no real way to inject these properly
  592. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  593. BaseItem.ConfigurationManager = ConfigurationManager;
  594. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  595. BaseItem.ProviderManager = Resolve<IProviderManager>();
  596. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  597. BaseItem.ItemRepository = Resolve<IItemRepository>();
  598. BaseItem.FileSystem = _fileSystemManager;
  599. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  600. BaseItem.ChannelManager = Resolve<IChannelManager>();
  601. Video.LiveTvManager = Resolve<ILiveTvManager>();
  602. Folder.UserViewManager = Resolve<IUserViewManager>();
  603. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  604. UserView.CollectionManager = Resolve<ICollectionManager>();
  605. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  606. CollectionFolder.XmlSerializer = _xmlSerializer;
  607. CollectionFolder.ApplicationHost = this;
  608. }
  609. /// <summary>
  610. /// Finds plugin components and register them with the appropriate services.
  611. /// </summary>
  612. private void FindParts()
  613. {
  614. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  615. {
  616. ConfigurationManager.Configuration.IsPortAuthorized = true;
  617. ConfigurationManager.SaveConfiguration();
  618. }
  619. _pluginManager.CreatePlugins();
  620. Resolve<ILibraryManager>().AddParts(
  621. GetExports<IResolverIgnoreRule>(),
  622. GetExports<IItemResolver>(),
  623. GetExports<IIntroProvider>(),
  624. GetExports<IBaseItemComparer>(),
  625. GetExports<ILibraryPostScanTask>());
  626. Resolve<IProviderManager>().AddParts(
  627. GetExports<IImageProvider>(),
  628. GetExports<IMetadataService>(),
  629. GetExports<IMetadataProvider>(),
  630. GetExports<IMetadataSaver>(),
  631. GetExports<IExternalId>());
  632. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  633. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  634. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  635. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  636. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  637. }
  638. /// <summary>
  639. /// Discovers the types.
  640. /// </summary>
  641. protected void DiscoverTypes()
  642. {
  643. Logger.LogInformation("Loading assemblies");
  644. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  645. }
  646. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  647. {
  648. foreach (var ass in assemblies)
  649. {
  650. Type[] exportedTypes;
  651. try
  652. {
  653. exportedTypes = ass.GetExportedTypes();
  654. }
  655. catch (FileNotFoundException ex)
  656. {
  657. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  658. _pluginManager.FailPlugin(ass);
  659. continue;
  660. }
  661. catch (TypeLoadException ex)
  662. {
  663. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  664. _pluginManager.FailPlugin(ass);
  665. continue;
  666. }
  667. foreach (Type type in exportedTypes)
  668. {
  669. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  670. {
  671. yield return type;
  672. }
  673. }
  674. }
  675. }
  676. /// <summary>
  677. /// Called when [configuration updated].
  678. /// </summary>
  679. /// <param name="sender">The sender.</param>
  680. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  681. private void OnConfigurationUpdated(object sender, EventArgs e)
  682. {
  683. var requiresRestart = false;
  684. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  685. // Don't do anything if these haven't been set yet
  686. if (HttpPort != 0 && HttpsPort != 0)
  687. {
  688. // Need to restart if ports have changed
  689. if (networkConfiguration.HttpServerPortNumber != HttpPort
  690. || networkConfiguration.HttpsPortNumber != HttpsPort)
  691. {
  692. if (ConfigurationManager.Configuration.IsPortAuthorized)
  693. {
  694. ConfigurationManager.Configuration.IsPortAuthorized = false;
  695. ConfigurationManager.SaveConfiguration();
  696. requiresRestart = true;
  697. }
  698. }
  699. }
  700. if (ValidateSslCertificate(networkConfiguration))
  701. {
  702. requiresRestart = true;
  703. }
  704. if (requiresRestart)
  705. {
  706. Logger.LogInformation("App needs to be restarted due to configuration change.");
  707. NotifyPendingRestart();
  708. }
  709. }
  710. /// <summary>
  711. /// Validates the SSL certificate.
  712. /// </summary>
  713. /// <param name="networkConfig">The new configuration.</param>
  714. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  715. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  716. {
  717. var newPath = networkConfig.CertificatePath;
  718. if (!string.IsNullOrWhiteSpace(newPath)
  719. && !string.Equals(CertificatePath, newPath, StringComparison.Ordinal))
  720. {
  721. if (File.Exists(newPath))
  722. {
  723. return true;
  724. }
  725. throw new FileNotFoundException(
  726. string.Format(
  727. CultureInfo.InvariantCulture,
  728. "Certificate file '{0}' does not exist.",
  729. newPath));
  730. }
  731. return false;
  732. }
  733. /// <summary>
  734. /// Notifies the kernel that a change has been made that requires a restart.
  735. /// </summary>
  736. public void NotifyPendingRestart()
  737. {
  738. Logger.LogInformation("App needs to be restarted.");
  739. var changed = !HasPendingRestart;
  740. HasPendingRestart = true;
  741. if (changed)
  742. {
  743. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  744. }
  745. }
  746. /// <summary>
  747. /// Restarts this instance.
  748. /// </summary>
  749. public void Restart()
  750. {
  751. if (!CanSelfRestart)
  752. {
  753. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  754. }
  755. if (IsShuttingDown)
  756. {
  757. return;
  758. }
  759. IsShuttingDown = true;
  760. Task.Run(async () =>
  761. {
  762. try
  763. {
  764. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  765. }
  766. catch (Exception ex)
  767. {
  768. Logger.LogError(ex, "Error sending server restart notification");
  769. }
  770. Logger.LogInformation("Calling RestartInternal");
  771. RestartInternal();
  772. });
  773. }
  774. protected abstract void RestartInternal();
  775. /// <summary>
  776. /// Gets the composable part assemblies.
  777. /// </summary>
  778. /// <returns>IEnumerable{Assembly}.</returns>
  779. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  780. {
  781. foreach (var p in _pluginManager.LoadAssemblies())
  782. {
  783. yield return p;
  784. }
  785. // Include composable parts in the Model assembly
  786. yield return typeof(SystemInfo).Assembly;
  787. // Include composable parts in the Common assembly
  788. yield return typeof(IApplicationHost).Assembly;
  789. // Include composable parts in the Controller assembly
  790. yield return typeof(IServerApplicationHost).Assembly;
  791. // Include composable parts in the Providers assembly
  792. yield return typeof(ProviderManager).Assembly;
  793. // Include composable parts in the Photos assembly
  794. yield return typeof(PhotoProvider).Assembly;
  795. // Emby.Server implementations
  796. yield return typeof(InstallationManager).Assembly;
  797. // MediaEncoding
  798. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  799. // Dlna
  800. yield return typeof(DlnaEntryPoint).Assembly;
  801. // Local metadata
  802. yield return typeof(BoxSetXmlSaver).Assembly;
  803. // Notifications
  804. yield return typeof(NotificationManager).Assembly;
  805. // Xbmc
  806. yield return typeof(ArtistNfoProvider).Assembly;
  807. // Network
  808. yield return typeof(NetworkManager).Assembly;
  809. // Hls
  810. yield return typeof(DynamicHlsPlaylistGenerator).Assembly;
  811. foreach (var i in GetAssembliesWithPartsInternal())
  812. {
  813. yield return i;
  814. }
  815. }
  816. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  817. /// <summary>
  818. /// Gets the system status.
  819. /// </summary>
  820. /// <param name="request">Where this request originated.</param>
  821. /// <returns>SystemInfo.</returns>
  822. public SystemInfo GetSystemInfo(HttpRequest request)
  823. {
  824. return new SystemInfo
  825. {
  826. HasPendingRestart = HasPendingRestart,
  827. IsShuttingDown = IsShuttingDown,
  828. Version = ApplicationVersionString,
  829. WebSocketPortNumber = HttpPort,
  830. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  831. Id = SystemId,
  832. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  833. WebPath = ApplicationPaths.WebPath,
  834. LogPath = ApplicationPaths.LogDirectoryPath,
  835. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  836. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  837. CachePath = ApplicationPaths.CachePath,
  838. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  839. OperatingSystemDisplayName = MediaBrowser.Common.System.OperatingSystem.Name,
  840. CanSelfRestart = CanSelfRestart,
  841. CanLaunchWebBrowser = CanLaunchWebBrowser,
  842. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  843. ServerName = FriendlyName,
  844. LocalAddress = GetSmartApiUrl(request),
  845. SupportsLibraryMonitor = true,
  846. SystemArchitecture = RuntimeInformation.OSArchitecture,
  847. PackageName = _startupOptions.PackageName
  848. };
  849. }
  850. public PublicSystemInfo GetPublicSystemInfo(HttpRequest request)
  851. {
  852. return new PublicSystemInfo
  853. {
  854. Version = ApplicationVersionString,
  855. ProductName = ApplicationProductName,
  856. Id = SystemId,
  857. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  858. ServerName = FriendlyName,
  859. LocalAddress = GetSmartApiUrl(request),
  860. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  861. };
  862. }
  863. /// <inheritdoc/>
  864. public string GetSmartApiUrl(IPAddress remoteAddr)
  865. {
  866. // Published server ends with a /
  867. if (!string.IsNullOrEmpty(PublishedServerUrl))
  868. {
  869. // Published server ends with a '/', so we need to remove it.
  870. return PublishedServerUrl.Trim('/');
  871. }
  872. string smart = NetManager.GetBindInterface(remoteAddr, out var port);
  873. return GetLocalApiUrl(smart.Trim('/'), null, port);
  874. }
  875. /// <inheritdoc/>
  876. public string GetSmartApiUrl(HttpRequest request)
  877. {
  878. // Return the host in the HTTP request as the API url
  879. if (ConfigurationManager.GetNetworkConfiguration().EnablePublishedServerUriByRequest)
  880. {
  881. int? requestPort = request.Host.Port;
  882. if ((requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase)) || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  883. {
  884. requestPort = -1;
  885. }
  886. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  887. }
  888. // Published server ends with a /
  889. if (!string.IsNullOrEmpty(PublishedServerUrl))
  890. {
  891. // Published server ends with a '/', so we need to remove it.
  892. return PublishedServerUrl.Trim('/');
  893. }
  894. string smart = NetManager.GetBindInterface(request, out var port);
  895. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  896. }
  897. /// <inheritdoc/>
  898. public string GetSmartApiUrl(string hostname)
  899. {
  900. // Published server ends with a /
  901. if (!string.IsNullOrEmpty(PublishedServerUrl))
  902. {
  903. // Published server ends with a '/', so we need to remove it.
  904. return PublishedServerUrl.Trim('/');
  905. }
  906. string smart = NetManager.GetBindInterface(hostname, out var port);
  907. return GetLocalApiUrl(smart.Trim('/'), null, port);
  908. }
  909. /// <inheritdoc/>
  910. public string GetApiUrlForLocalAccess(IPObject hostname = null, bool allowHttps = true)
  911. {
  912. // With an empty source, the port will be null
  913. var smart = NetManager.GetBindInterface(hostname ?? IPHost.None, out _);
  914. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  915. int? port = !allowHttps ? HttpPort : null;
  916. return GetLocalApiUrl(smart, scheme, port);
  917. }
  918. /// <inheritdoc/>
  919. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  920. {
  921. // If the smartAPI doesn't start with http then treat it as a host or ip.
  922. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  923. {
  924. return hostname.TrimEnd('/');
  925. }
  926. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  927. // not. For consistency, always trim the trailing slash.
  928. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  929. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  930. return new UriBuilder
  931. {
  932. Scheme = scheme,
  933. Host = hostname,
  934. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  935. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  936. }.ToString().TrimEnd('/');
  937. }
  938. /// <inheritdoc />
  939. public async Task Shutdown()
  940. {
  941. if (IsShuttingDown)
  942. {
  943. return;
  944. }
  945. IsShuttingDown = true;
  946. try
  947. {
  948. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  949. }
  950. catch (Exception ex)
  951. {
  952. Logger.LogError(ex, "Error sending server shutdown notification");
  953. }
  954. ShutdownInternal();
  955. }
  956. protected abstract void ShutdownInternal();
  957. public IEnumerable<Assembly> GetApiPluginAssemblies()
  958. {
  959. var assemblies = _allConcreteTypes
  960. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  961. .Select(i => i.Assembly)
  962. .Distinct();
  963. foreach (var assembly in assemblies)
  964. {
  965. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  966. yield return assembly;
  967. }
  968. }
  969. /// <inheritdoc />
  970. public void Dispose()
  971. {
  972. Dispose(true);
  973. GC.SuppressFinalize(this);
  974. }
  975. /// <summary>
  976. /// Releases unmanaged and - optionally - managed resources.
  977. /// </summary>
  978. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  979. protected virtual void Dispose(bool dispose)
  980. {
  981. if (_disposed)
  982. {
  983. return;
  984. }
  985. if (dispose)
  986. {
  987. var type = GetType();
  988. Logger.LogInformation("Disposing {Type}", type.Name);
  989. foreach (var (part, _) in _disposableParts)
  990. {
  991. var partType = part.GetType();
  992. if (partType == type)
  993. {
  994. continue;
  995. }
  996. Logger.LogInformation("Disposing {Type}", partType.Name);
  997. try
  998. {
  999. part.Dispose();
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  1004. }
  1005. }
  1006. _disposableParts.Clear();
  1007. }
  1008. _disposed = true;
  1009. }
  1010. }
  1011. }