ApplicationHost.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  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 CertificateInfo CertificateInfo { 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. CertificateInfo = new CertificateInfo
  465. {
  466. Path = networkConfiguration.CertificatePath,
  467. Password = networkConfiguration.CertificatePassword
  468. };
  469. Certificate = GetCertificate(CertificateInfo);
  470. RegisterServices();
  471. _pluginManager.RegisterServices(ServiceCollection);
  472. }
  473. /// <summary>
  474. /// Registers services/resources with the service collection that will be available via DI.
  475. /// </summary>
  476. protected virtual void RegisterServices()
  477. {
  478. ServiceCollection.AddSingleton(_startupOptions);
  479. ServiceCollection.AddMemoryCache();
  480. ServiceCollection.AddSingleton<IServerConfigurationManager>(ConfigurationManager);
  481. ServiceCollection.AddSingleton<IConfigurationManager>(ConfigurationManager);
  482. ServiceCollection.AddSingleton<IApplicationHost>(this);
  483. ServiceCollection.AddSingleton<IPluginManager>(_pluginManager);
  484. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  485. ServiceCollection.AddSingleton(_fileSystemManager);
  486. ServiceCollection.AddSingleton<TmdbClientManager>();
  487. ServiceCollection.AddSingleton(NetManager);
  488. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  489. ServiceCollection.AddSingleton(_xmlSerializer);
  490. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  491. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  492. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  493. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  494. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  495. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  496. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  497. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  498. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  499. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  500. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  501. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  502. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  503. ServiceCollection.AddSingleton<EncodingHelper>();
  504. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  505. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  506. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  507. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  508. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  509. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  510. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  511. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  512. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  513. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  514. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  515. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  516. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  517. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  518. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  519. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  520. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  521. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  522. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  523. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  524. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  525. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  526. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  527. ServiceCollection.AddSingleton<LiveTvDtoService>();
  528. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  529. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  530. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  531. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  532. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  533. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  534. ServiceCollection.AddScoped<ISessionContext, SessionContext>();
  535. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  536. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  537. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  538. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  539. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  540. ServiceCollection.AddScoped<MediaInfoHelper>();
  541. ServiceCollection.AddScoped<AudioHelper>();
  542. ServiceCollection.AddScoped<DynamicHlsHelper>();
  543. ServiceCollection.AddSingleton<IDirectoryService, DirectoryService>();
  544. }
  545. /// <summary>
  546. /// Create services registered with the service container that need to be initialized at application startup.
  547. /// </summary>
  548. /// <returns>A task representing the service initialization operation.</returns>
  549. public async Task InitializeServices()
  550. {
  551. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  552. await localizationManager.LoadAll().ConfigureAwait(false);
  553. _mediaEncoder = Resolve<IMediaEncoder>();
  554. _sessionManager = Resolve<ISessionManager>();
  555. SetStaticProperties();
  556. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  557. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  558. FindParts();
  559. }
  560. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  561. {
  562. // Distinct these to prevent users from reporting problems that aren't actually problems
  563. var commandLineArgs = Environment
  564. .GetCommandLineArgs()
  565. .Distinct();
  566. // Get all relevant environment variables
  567. var allEnvVars = Environment.GetEnvironmentVariables();
  568. var relevantEnvVars = new Dictionary<object, object>();
  569. foreach (var key in allEnvVars.Keys)
  570. {
  571. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  572. {
  573. relevantEnvVars.Add(key, allEnvVars[key]);
  574. }
  575. }
  576. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  577. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  578. logger.LogInformation("Operating system: {OS}", MediaBrowser.Common.System.OperatingSystem.Name);
  579. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  580. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  581. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  582. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  583. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  584. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  585. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  586. }
  587. private X509Certificate2 GetCertificate(CertificateInfo info)
  588. {
  589. var certificateLocation = info?.Path;
  590. if (string.IsNullOrWhiteSpace(certificateLocation))
  591. {
  592. return null;
  593. }
  594. try
  595. {
  596. if (!File.Exists(certificateLocation))
  597. {
  598. return null;
  599. }
  600. // Don't use an empty string password
  601. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  602. var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet);
  603. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  604. if (!localCert.HasPrivateKey)
  605. {
  606. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  607. return null;
  608. }
  609. return localCert;
  610. }
  611. catch (Exception ex)
  612. {
  613. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  614. return null;
  615. }
  616. }
  617. /// <summary>
  618. /// Dirty hacks.
  619. /// </summary>
  620. private void SetStaticProperties()
  621. {
  622. // For now there's no real way to inject these properly
  623. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  624. BaseItem.ConfigurationManager = ConfigurationManager;
  625. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  626. BaseItem.ProviderManager = Resolve<IProviderManager>();
  627. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  628. BaseItem.ItemRepository = Resolve<IItemRepository>();
  629. BaseItem.FileSystem = _fileSystemManager;
  630. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  631. BaseItem.ChannelManager = Resolve<IChannelManager>();
  632. Video.LiveTvManager = Resolve<ILiveTvManager>();
  633. Folder.UserViewManager = Resolve<IUserViewManager>();
  634. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  635. UserView.CollectionManager = Resolve<ICollectionManager>();
  636. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  637. CollectionFolder.XmlSerializer = _xmlSerializer;
  638. CollectionFolder.ApplicationHost = this;
  639. }
  640. /// <summary>
  641. /// Finds plugin components and register them with the appropriate services.
  642. /// </summary>
  643. private void FindParts()
  644. {
  645. if (!ConfigurationManager.Configuration.IsPortAuthorized)
  646. {
  647. ConfigurationManager.Configuration.IsPortAuthorized = true;
  648. ConfigurationManager.SaveConfiguration();
  649. }
  650. _pluginManager.CreatePlugins();
  651. _urlPrefixes = GetUrlPrefixes().ToArray();
  652. Resolve<ILibraryManager>().AddParts(
  653. GetExports<IResolverIgnoreRule>(),
  654. GetExports<IItemResolver>(),
  655. GetExports<IIntroProvider>(),
  656. GetExports<IBaseItemComparer>(),
  657. GetExports<ILibraryPostScanTask>());
  658. Resolve<IProviderManager>().AddParts(
  659. GetExports<IImageProvider>(),
  660. GetExports<IMetadataService>(),
  661. GetExports<IMetadataProvider>(),
  662. GetExports<IMetadataSaver>(),
  663. GetExports<IExternalId>());
  664. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  665. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  666. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  667. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  668. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  669. }
  670. /// <summary>
  671. /// Discovers the types.
  672. /// </summary>
  673. protected void DiscoverTypes()
  674. {
  675. Logger.LogInformation("Loading assemblies");
  676. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  677. }
  678. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  679. {
  680. foreach (var ass in assemblies)
  681. {
  682. Type[] exportedTypes;
  683. try
  684. {
  685. exportedTypes = ass.GetExportedTypes();
  686. }
  687. catch (FileNotFoundException ex)
  688. {
  689. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  690. _pluginManager.FailPlugin(ass);
  691. continue;
  692. }
  693. catch (TypeLoadException ex)
  694. {
  695. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  696. _pluginManager.FailPlugin(ass);
  697. continue;
  698. }
  699. foreach (Type type in exportedTypes)
  700. {
  701. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  702. {
  703. yield return type;
  704. }
  705. }
  706. }
  707. }
  708. private IEnumerable<string> GetUrlPrefixes()
  709. {
  710. var hosts = new[] { "+" };
  711. return hosts.SelectMany(i =>
  712. {
  713. var prefixes = new List<string>
  714. {
  715. "http://" + i + ":" + HttpPort + "/"
  716. };
  717. if (CertificateInfo != null)
  718. {
  719. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  720. }
  721. return prefixes;
  722. });
  723. }
  724. /// <summary>
  725. /// Called when [configuration updated].
  726. /// </summary>
  727. /// <param name="sender">The sender.</param>
  728. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  729. protected void OnConfigurationUpdated(object sender, EventArgs e)
  730. {
  731. var requiresRestart = false;
  732. var networkConfiguration = ConfigurationManager.GetNetworkConfiguration();
  733. // Don't do anything if these haven't been set yet
  734. if (HttpPort != 0 && HttpsPort != 0)
  735. {
  736. // Need to restart if ports have changed
  737. if (networkConfiguration.HttpServerPortNumber != HttpPort ||
  738. networkConfiguration.HttpsPortNumber != HttpsPort)
  739. {
  740. if (ConfigurationManager.Configuration.IsPortAuthorized)
  741. {
  742. ConfigurationManager.Configuration.IsPortAuthorized = false;
  743. ConfigurationManager.SaveConfiguration();
  744. requiresRestart = true;
  745. }
  746. }
  747. }
  748. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  749. {
  750. requiresRestart = true;
  751. }
  752. if (ValidateSslCertificate(networkConfiguration))
  753. {
  754. requiresRestart = true;
  755. }
  756. if (requiresRestart)
  757. {
  758. Logger.LogInformation("App needs to be restarted due to configuration change.");
  759. NotifyPendingRestart();
  760. }
  761. }
  762. /// <summary>
  763. /// Validates the SSL certificate.
  764. /// </summary>
  765. /// <param name="networkConfig">The new configuration.</param>
  766. /// <exception cref="FileNotFoundException">The certificate path doesn't exist.</exception>
  767. private bool ValidateSslCertificate(NetworkConfiguration networkConfig)
  768. {
  769. var newPath = networkConfig.CertificatePath;
  770. if (!string.IsNullOrWhiteSpace(newPath)
  771. && !string.Equals(CertificateInfo?.Path, newPath, StringComparison.Ordinal))
  772. {
  773. if (File.Exists(newPath))
  774. {
  775. return true;
  776. }
  777. throw new FileNotFoundException(
  778. string.Format(
  779. CultureInfo.InvariantCulture,
  780. "Certificate file '{0}' does not exist.",
  781. newPath));
  782. }
  783. return false;
  784. }
  785. /// <summary>
  786. /// Notifies that the kernel that a change has been made that requires a restart.
  787. /// </summary>
  788. public void NotifyPendingRestart()
  789. {
  790. Logger.LogInformation("App needs to be restarted.");
  791. var changed = !HasPendingRestart;
  792. HasPendingRestart = true;
  793. if (changed)
  794. {
  795. EventHelper.QueueEventIfNotNull(HasPendingRestartChanged, this, EventArgs.Empty, Logger);
  796. }
  797. }
  798. /// <summary>
  799. /// Restarts this instance.
  800. /// </summary>
  801. public void Restart()
  802. {
  803. if (!CanSelfRestart)
  804. {
  805. throw new PlatformNotSupportedException("The server is unable to self-restart. Please restart manually.");
  806. }
  807. if (IsShuttingDown)
  808. {
  809. return;
  810. }
  811. IsShuttingDown = true;
  812. Task.Run(async () =>
  813. {
  814. try
  815. {
  816. await _sessionManager.SendServerRestartNotification(CancellationToken.None).ConfigureAwait(false);
  817. }
  818. catch (Exception ex)
  819. {
  820. Logger.LogError(ex, "Error sending server restart notification");
  821. }
  822. Logger.LogInformation("Calling RestartInternal");
  823. RestartInternal();
  824. });
  825. }
  826. protected abstract void RestartInternal();
  827. /// <summary>
  828. /// Gets the composable part assemblies.
  829. /// </summary>
  830. /// <returns>IEnumerable{Assembly}.</returns>
  831. protected IEnumerable<Assembly> GetComposablePartAssemblies()
  832. {
  833. foreach (var p in _pluginManager.LoadAssemblies())
  834. {
  835. yield return p;
  836. }
  837. // Include composable parts in the Model assembly
  838. yield return typeof(SystemInfo).Assembly;
  839. // Include composable parts in the Common assembly
  840. yield return typeof(IApplicationHost).Assembly;
  841. // Include composable parts in the Controller assembly
  842. yield return typeof(IServerApplicationHost).Assembly;
  843. // Include composable parts in the Providers assembly
  844. yield return typeof(ProviderUtils).Assembly;
  845. // Include composable parts in the Photos assembly
  846. yield return typeof(PhotoProvider).Assembly;
  847. // Emby.Server implementations
  848. yield return typeof(InstallationManager).Assembly;
  849. // MediaEncoding
  850. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  851. // Dlna
  852. yield return typeof(DlnaEntryPoint).Assembly;
  853. // Local metadata
  854. yield return typeof(BoxSetXmlSaver).Assembly;
  855. // Notifications
  856. yield return typeof(NotificationManager).Assembly;
  857. // Xbmc
  858. yield return typeof(ArtistNfoProvider).Assembly;
  859. // Network
  860. yield return typeof(NetworkManager).Assembly;
  861. foreach (var i in GetAssembliesWithPartsInternal())
  862. {
  863. yield return i;
  864. }
  865. }
  866. protected abstract IEnumerable<Assembly> GetAssembliesWithPartsInternal();
  867. /// <summary>
  868. /// Gets the system status.
  869. /// </summary>
  870. /// <param name="source">Where this request originated.</param>
  871. /// <returns>SystemInfo.</returns>
  872. public SystemInfo GetSystemInfo(IPAddress source)
  873. {
  874. return new SystemInfo
  875. {
  876. HasPendingRestart = HasPendingRestart,
  877. IsShuttingDown = IsShuttingDown,
  878. Version = ApplicationVersionString,
  879. WebSocketPortNumber = HttpPort,
  880. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  881. Id = SystemId,
  882. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  883. WebPath = ApplicationPaths.WebPath,
  884. LogPath = ApplicationPaths.LogDirectoryPath,
  885. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  886. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  887. CachePath = ApplicationPaths.CachePath,
  888. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  889. OperatingSystemDisplayName = MediaBrowser.Common.System.OperatingSystem.Name,
  890. CanSelfRestart = CanSelfRestart,
  891. CanLaunchWebBrowser = CanLaunchWebBrowser,
  892. TranscodingTempPath = ConfigurationManager.GetTranscodePath(),
  893. ServerName = FriendlyName,
  894. LocalAddress = GetSmartApiUrl(source),
  895. SupportsLibraryMonitor = true,
  896. SystemArchitecture = RuntimeInformation.OSArchitecture,
  897. PackageName = _startupOptions.PackageName
  898. };
  899. }
  900. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  901. => NetManager.GetMacAddresses()
  902. .Select(i => new WakeOnLanInfo(i))
  903. .ToList();
  904. public PublicSystemInfo GetPublicSystemInfo(IPAddress address)
  905. {
  906. return new PublicSystemInfo
  907. {
  908. Version = ApplicationVersionString,
  909. ProductName = ApplicationProductName,
  910. Id = SystemId,
  911. OperatingSystem = MediaBrowser.Common.System.OperatingSystem.Id.ToString(),
  912. ServerName = FriendlyName,
  913. LocalAddress = GetSmartApiUrl(address),
  914. StartupWizardCompleted = ConfigurationManager.CommonConfiguration.IsStartupWizardCompleted
  915. };
  916. }
  917. /// <inheritdoc/>
  918. public string GetSmartApiUrl(IPAddress remoteAddr, int? port = null)
  919. {
  920. // Published server ends with a /
  921. if (!string.IsNullOrEmpty(PublishedServerUrl))
  922. {
  923. // Published server ends with a '/', so we need to remove it.
  924. return PublishedServerUrl.Trim('/');
  925. }
  926. string smart = NetManager.GetBindInterface(remoteAddr, out port);
  927. // If the smartAPI doesn't start with http then treat it as a host or ip.
  928. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  929. {
  930. return smart.Trim('/');
  931. }
  932. return GetLocalApiUrl(smart.Trim('/'), null, port);
  933. }
  934. /// <inheritdoc/>
  935. public string GetSmartApiUrl(HttpRequest request, int? port = null)
  936. {
  937. // Published server ends with a /
  938. if (!string.IsNullOrEmpty(PublishedServerUrl))
  939. {
  940. // Published server ends with a '/', so we need to remove it.
  941. return PublishedServerUrl.Trim('/');
  942. }
  943. string smart = NetManager.GetBindInterface(request, out port);
  944. // If the smartAPI doesn't start with http then treat it as a host or ip.
  945. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  946. {
  947. return smart.Trim('/');
  948. }
  949. return GetLocalApiUrl(smart.Trim('/'), request.Scheme, port);
  950. }
  951. /// <inheritdoc/>
  952. public string GetSmartApiUrl(string hostname, int? port = null)
  953. {
  954. // Published server ends with a /
  955. if (!string.IsNullOrEmpty(PublishedServerUrl))
  956. {
  957. // Published server ends with a '/', so we need to remove it.
  958. return PublishedServerUrl.Trim('/');
  959. }
  960. string smart = NetManager.GetBindInterface(hostname, out port);
  961. // If the smartAPI doesn't start with http then treat it as a host or ip.
  962. if (smart.StartsWith("http", StringComparison.OrdinalIgnoreCase))
  963. {
  964. return smart.Trim('/');
  965. }
  966. return GetLocalApiUrl(smart.Trim('/'), null, port);
  967. }
  968. /// <inheritdoc/>
  969. public string GetLoopbackHttpApiUrl()
  970. {
  971. if (NetManager.IsIP6Enabled)
  972. {
  973. return GetLocalApiUrl("::1", Uri.UriSchemeHttp, HttpPort);
  974. }
  975. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  976. }
  977. /// <inheritdoc/>
  978. public string GetLocalApiUrl(string hostname, string scheme = null, int? port = null)
  979. {
  980. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  981. // not. For consistency, always trim the trailing slash.
  982. return new UriBuilder
  983. {
  984. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  985. Host = hostname,
  986. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  987. Path = ConfigurationManager.GetNetworkConfiguration().BaseUrl
  988. }.ToString().TrimEnd('/');
  989. }
  990. /// <inheritdoc />
  991. public async Task Shutdown()
  992. {
  993. if (IsShuttingDown)
  994. {
  995. return;
  996. }
  997. IsShuttingDown = true;
  998. try
  999. {
  1000. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1001. }
  1002. catch (Exception ex)
  1003. {
  1004. Logger.LogError(ex, "Error sending server shutdown notification");
  1005. }
  1006. ShutdownInternal();
  1007. }
  1008. protected abstract void ShutdownInternal();
  1009. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1010. {
  1011. var assemblies = _allConcreteTypes
  1012. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1013. .Select(i => i.Assembly)
  1014. .Distinct();
  1015. foreach (var assembly in assemblies)
  1016. {
  1017. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1018. yield return assembly;
  1019. }
  1020. }
  1021. /// <inheritdoc />
  1022. public void Dispose()
  1023. {
  1024. Dispose(true);
  1025. GC.SuppressFinalize(this);
  1026. }
  1027. /// <summary>
  1028. /// Releases unmanaged and - optionally - managed resources.
  1029. /// </summary>
  1030. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1031. protected virtual void Dispose(bool dispose)
  1032. {
  1033. if (_disposed)
  1034. {
  1035. return;
  1036. }
  1037. if (dispose)
  1038. {
  1039. var type = GetType();
  1040. Logger.LogInformation("Disposing {Type}", type.Name);
  1041. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1042. _disposableParts.Clear();
  1043. foreach (var part in parts)
  1044. {
  1045. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1046. try
  1047. {
  1048. part.Dispose();
  1049. }
  1050. catch (Exception ex)
  1051. {
  1052. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1053. }
  1054. }
  1055. }
  1056. _disposed = true;
  1057. }
  1058. }
  1059. internal class CertificateInfo
  1060. {
  1061. public string Path { get; set; }
  1062. public string Password { get; set; }
  1063. }
  1064. }