ApplicationHost.cs 46 KB

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