ApplicationHost.cs 48 KB

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