ApplicationHost.cs 51 KB

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