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