ApplicationHost.cs 51 KB

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