ApplicationHost.cs 48 KB

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