ApplicationHost.cs 50 KB

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