ApplicationHost.cs 52 KB

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