ApplicationHost.cs 52 KB

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