ApplicationHost.cs 48 KB

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