ApplicationHost.cs 49 KB

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