ApplicationHost.cs 49 KB

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