ApplicationHost.cs 48 KB

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