ApplicationHost.cs 49 KB

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