ApplicationHost.cs 51 KB

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