ApplicationHost.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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.GetBindAddress(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 == null
  888. || (requestPort == 80 && string.Equals(request.Scheme, "http", StringComparison.OrdinalIgnoreCase))
  889. || (requestPort == 443 && string.Equals(request.Scheme, "https", StringComparison.OrdinalIgnoreCase)))
  890. {
  891. requestPort = -1;
  892. }
  893. return GetLocalApiUrl(request.Host.Host, request.Scheme, requestPort);
  894. }
  895. return GetSmartApiUrl(request.HttpContext.Connection.RemoteIpAddress ?? IPAddress.Loopback);
  896. }
  897. /// <inheritdoc/>
  898. public string GetSmartApiUrl(string hostname)
  899. {
  900. // Published server ends with a /
  901. if (!string.IsNullOrEmpty(PublishedServerUrl))
  902. {
  903. // Published server ends with a '/', so we need to remove it.
  904. return PublishedServerUrl.Trim('/');
  905. }
  906. string smart = NetManager.GetBindInterface(hostname, out var port);
  907. return GetLocalApiUrl(smart.Trim('/'), null, port);
  908. }
  909. /// <inheritdoc/>
  910. public string GetApiUrlForLocalAccess(IPAddress ipAddress = null, bool allowHttps = true)
  911. {
  912. // With an empty source, the port will be null
  913. var smart = NetManager.GetBindAddress(ipAddress, out _);
  914. var scheme = !allowHttps ? Uri.UriSchemeHttp : null;
  915. int? port = !allowHttps ? HttpPort : null;
  916. return GetLocalApiUrl(smart, scheme, port);
  917. }
  918. /// <inheritdoc/>
  919. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  920. {
  921. // If the smartAPI doesn't start with http then treat it as a host or ip.
  922. if (hostname.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  923. {
  924. return hostname.TrimEnd('/');
  925. }
  926. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  927. // not. For consistency, always trim the trailing slash.
  928. scheme ??= ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;
  929. var isHttps = string.Equals(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase);
  930. return new UriBuilder
  931. {
  932. Scheme = scheme,
  933. Host = hostname,
  934. Port = port ?? (isHttps ? HttpsPort : HttpPort),
  935. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  936. }.ToString().TrimEnd('/');
  937. }
  938. /// <inheritdoc />
  939. public async Task Shutdown()
  940. {
  941. if (IsShuttingDown)
  942. {
  943. return;
  944. }
  945. IsShuttingDown = true;
  946. try
  947. {
  948. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  949. }
  950. catch (Exception ex)
  951. {
  952. Logger.LogError(ex, "Error sending server shutdown notification");
  953. }
  954. ShutdownInternal();
  955. }
  956. protected abstract void ShutdownInternal();
  957. public IEnumerable<Assembly> GetApiPluginAssemblies()
  958. {
  959. var assemblies = _allConcreteTypes
  960. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  961. .Select(i => i.Assembly)
  962. .Distinct();
  963. foreach (var assembly in assemblies)
  964. {
  965. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  966. yield return assembly;
  967. }
  968. }
  969. /// <inheritdoc />
  970. public void Dispose()
  971. {
  972. Dispose(true);
  973. GC.SuppressFinalize(this);
  974. }
  975. /// <summary>
  976. /// Releases unmanaged and - optionally - managed resources.
  977. /// </summary>
  978. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  979. protected virtual void Dispose(bool dispose)
  980. {
  981. if (_disposed)
  982. {
  983. return;
  984. }
  985. if (dispose)
  986. {
  987. var type = GetType();
  988. Logger.LogInformation("Disposing {Type}", type.Name);
  989. foreach (var (part, _) in _disposableParts)
  990. {
  991. var partType = part.GetType();
  992. if (partType == type)
  993. {
  994. continue;
  995. }
  996. Logger.LogInformation("Disposing {Type}", partType.Name);
  997. try
  998. {
  999. part.Dispose();
  1000. }
  1001. catch (Exception ex)
  1002. {
  1003. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  1004. }
  1005. }
  1006. _disposableParts.Clear();
  1007. }
  1008. _disposed = true;
  1009. }
  1010. public async ValueTask DisposeAsync()
  1011. {
  1012. await DisposeAsyncCore().ConfigureAwait(false);
  1013. Dispose(false);
  1014. GC.SuppressFinalize(this);
  1015. }
  1016. /// <summary>
  1017. /// Used to perform asynchronous cleanup of managed resources or for cascading calls to <see cref="DisposeAsync"/>.
  1018. /// </summary>
  1019. /// <returns>A ValueTask.</returns>
  1020. protected virtual async ValueTask DisposeAsyncCore()
  1021. {
  1022. var type = GetType();
  1023. Logger.LogInformation("Disposing {Type}", type.Name);
  1024. foreach (var (part, _) in _disposableParts)
  1025. {
  1026. var partType = part.GetType();
  1027. if (partType == type)
  1028. {
  1029. continue;
  1030. }
  1031. Logger.LogInformation("Disposing {Type}", partType.Name);
  1032. try
  1033. {
  1034. part.Dispose();
  1035. }
  1036. catch (Exception ex)
  1037. {
  1038. Logger.LogError(ex, "Error disposing {Type}", partType.Name);
  1039. }
  1040. }
  1041. // used for closing websockets
  1042. foreach (var session in _sessionManager.Sessions)
  1043. {
  1044. await session.DisposeAsync().ConfigureAwait(false);
  1045. }
  1046. }
  1047. }
  1048. }