ApplicationHost.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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.Text;
  13. using System.Text.Json;
  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.Json;
  54. using MediaBrowser.Common.Net;
  55. using MediaBrowser.Common.Plugins;
  56. using MediaBrowser.Common.Updates;
  57. using MediaBrowser.Controller;
  58. using MediaBrowser.Controller.Channels;
  59. using MediaBrowser.Controller.Chapters;
  60. using MediaBrowser.Controller.Collections;
  61. using MediaBrowser.Controller.Configuration;
  62. using MediaBrowser.Controller.Devices;
  63. using MediaBrowser.Controller.Dlna;
  64. using MediaBrowser.Controller.Drawing;
  65. using MediaBrowser.Controller.Dto;
  66. using MediaBrowser.Controller.Entities;
  67. using MediaBrowser.Controller.Library;
  68. using MediaBrowser.Controller.LiveTv;
  69. using MediaBrowser.Controller.MediaEncoding;
  70. using MediaBrowser.Controller.Net;
  71. using MediaBrowser.Controller.Notifications;
  72. using MediaBrowser.Controller.Persistence;
  73. using MediaBrowser.Controller.Playlists;
  74. using MediaBrowser.Controller.Plugins;
  75. using MediaBrowser.Controller.Providers;
  76. using MediaBrowser.Controller.QuickConnect;
  77. using MediaBrowser.Controller.Resolvers;
  78. using MediaBrowser.Controller.Security;
  79. using MediaBrowser.Controller.Session;
  80. using MediaBrowser.Controller.Sorting;
  81. using MediaBrowser.Controller.Subtitles;
  82. using MediaBrowser.Controller.SyncPlay;
  83. using MediaBrowser.Controller.TV;
  84. using MediaBrowser.LocalMetadata.Savers;
  85. using MediaBrowser.MediaEncoding.BdInfo;
  86. using MediaBrowser.Model.Cryptography;
  87. using MediaBrowser.Model.Dlna;
  88. using MediaBrowser.Model.Globalization;
  89. using MediaBrowser.Model.IO;
  90. using MediaBrowser.Model.MediaInfo;
  91. using MediaBrowser.Model.Net;
  92. using MediaBrowser.Model.Serialization;
  93. using MediaBrowser.Model.System;
  94. using MediaBrowser.Model.Tasks;
  95. using MediaBrowser.Providers.Chapters;
  96. using MediaBrowser.Providers.Manager;
  97. using MediaBrowser.Providers.Plugins.Tmdb;
  98. using MediaBrowser.Providers.Subtitles;
  99. using MediaBrowser.XbmcMetadata.Providers;
  100. using Microsoft.AspNetCore.Http;
  101. using Microsoft.AspNetCore.Mvc;
  102. using Microsoft.Extensions.Configuration;
  103. using Microsoft.Extensions.DependencyInjection;
  104. using Microsoft.Extensions.Logging;
  105. using Prometheus.DotNetRuntime;
  106. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  107. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  108. namespace Emby.Server.Implementations
  109. {
  110. /// <summary>
  111. /// Class CompositionRoot.
  112. /// </summary>
  113. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  114. {
  115. /// <summary>
  116. /// The environment variable prefixes to log at server startup.
  117. /// </summary>
  118. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  119. private readonly IFileSystem _fileSystemManager;
  120. private readonly IConfiguration _startupConfig;
  121. private readonly IXmlSerializer _xmlSerializer;
  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. ServiceCollection = serviceCollection;
  236. ApplicationPaths = applicationPaths;
  237. LoggerFactory = loggerFactory;
  238. _fileSystemManager = fileSystem;
  239. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  240. // Have to migrate settings here as migration subsystem not yet initialised.
  241. MigrateNetworkConfiguration();
  242. // Have to pre-register the NetworkConfigurationFactory, as the configuration sub-system is not yet initialised.
  243. ConfigurationManager.RegisterConfiguration<NetworkConfigurationFactory>();
  244. NetManager = new NetworkManager((IServerConfigurationManager)ConfigurationManager, LoggerFactory.CreateLogger<NetworkManager>());
  245. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  246. _startupOptions = options;
  247. _startupConfig = startupConfig;
  248. // Initialize runtime stat collection
  249. if (ServerConfigurationManager.Configuration.EnableMetrics)
  250. {
  251. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  252. }
  253. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  254. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  255. ApplicationVersionString = ApplicationVersion.ToString(3);
  256. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  257. _pluginManager = new PluginManager(
  258. LoggerFactory.CreateLogger<PluginManager>(),
  259. this,
  260. ServerConfigurationManager.Configuration,
  261. ApplicationPaths.PluginsPath,
  262. ApplicationVersion);
  263. }
  264. /// <summary>
  265. /// Temporary function to migration network settings out of system.xml and into network.xml.
  266. /// TODO: remove at the point when a fixed migration path has been decided upon.
  267. /// </summary>
  268. private void MigrateNetworkConfiguration()
  269. {
  270. string path = Path.Combine(ConfigurationManager.CommonApplicationPaths.ConfigurationDirectoryPath, "network.xml");
  271. if (!File.Exists(path))
  272. {
  273. var networkSettings = new NetworkConfiguration();
  274. ClassMigrationHelper.CopyProperties(ServerConfigurationManager.Configuration, networkSettings);
  275. _xmlSerializer.SerializeToFile(networkSettings, path);
  276. Logger?.LogDebug("Successfully migrated network settings.");
  277. }
  278. }
  279. public string ExpandVirtualPath(string path)
  280. {
  281. var appPaths = ApplicationPaths;
  282. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  283. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  284. }
  285. public string ReverseVirtualPath(string path)
  286. {
  287. var appPaths = ApplicationPaths;
  288. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  289. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  290. }
  291. /// <inheritdoc />
  292. public Version ApplicationVersion { get; }
  293. /// <inheritdoc />
  294. public string ApplicationVersionString { get; }
  295. /// <summary>
  296. /// Gets the current application user agent.
  297. /// </summary>
  298. /// <value>The application user agent.</value>
  299. public string ApplicationUserAgent { get; }
  300. /// <summary>
  301. /// Gets the email address for use within a comment section of a user agent field.
  302. /// Presently used to provide contact information to MusicBrainz service.
  303. /// </summary>
  304. public string ApplicationUserAgentAddress => "team@jellyfin.org";
  305. /// <summary>
  306. /// Gets the current application name.
  307. /// </summary>
  308. /// <value>The application name.</value>
  309. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  310. private DeviceId _deviceId;
  311. public string SystemId
  312. {
  313. get
  314. {
  315. if (_deviceId == null)
  316. {
  317. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  318. }
  319. return _deviceId.Value;
  320. }
  321. }
  322. /// <inheritdoc/>
  323. public string Name => ApplicationProductName;
  324. /// <summary>
  325. /// Creates an instance of type and resolves all constructor dependencies.
  326. /// </summary>
  327. /// <param name="type">The type.</param>
  328. /// <returns>System.Object.</returns>
  329. public object CreateInstance(Type type)
  330. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  331. /// <summary>
  332. /// Creates an instance of type and resolves all constructor dependencies.
  333. /// </summary>
  334. /// <typeparam name="T">The type.</typeparam>
  335. /// <returns>T.</returns>
  336. public T CreateInstance<T>()
  337. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  338. /// <summary>
  339. /// Creates the instance safe.
  340. /// </summary>
  341. /// <param name="type">The type.</param>
  342. /// <returns>System.Object.</returns>
  343. protected object CreateInstanceSafe(Type type)
  344. {
  345. if (_creatingInstances == null)
  346. {
  347. _creatingInstances = new List<Type>();
  348. }
  349. if (_creatingInstances.IndexOf(type) != -1)
  350. {
  351. Logger.LogError("DI Loop detected in the attempted creation of {Type}", type.FullName);
  352. foreach (var entry in _creatingInstances)
  353. {
  354. Logger.LogError("Called from: {TypeName}", entry.FullName);
  355. }
  356. _pluginManager.FailPlugin(type.Assembly);
  357. throw new ExternalException("DI Loop detected.");
  358. }
  359. try
  360. {
  361. _creatingInstances.Add(type);
  362. Logger.LogDebug("Creating instance of {Type}", type);
  363. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  364. }
  365. catch (Exception ex)
  366. {
  367. Logger.LogError(ex, "Error creating {Type}", type);
  368. // If this is a plugin fail it.
  369. _pluginManager.FailPlugin(type.Assembly);
  370. return null;
  371. }
  372. finally
  373. {
  374. _creatingInstances.Remove(type);
  375. }
  376. }
  377. /// <summary>
  378. /// Resolves this instance.
  379. /// </summary>
  380. /// <typeparam name="T">The type.</typeparam>
  381. /// <returns>``0.</returns>
  382. public T Resolve<T>() => ServiceProvider.GetService<T>();
  383. /// <inheritdoc/>
  384. public IEnumerable<Type> GetExportTypes<T>()
  385. {
  386. var currentType = typeof(T);
  387. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  388. }
  389. /// <inheritdoc />
  390. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  391. {
  392. // Convert to list so this isn't executed for each iteration
  393. var parts = GetExportTypes<T>()
  394. .Select(CreateInstanceSafe)
  395. .Where(i => i != null)
  396. .Cast<T>()
  397. .ToList();
  398. if (manageLifetime)
  399. {
  400. lock (_disposableParts)
  401. {
  402. _disposableParts.AddRange(parts.OfType<IDisposable>());
  403. }
  404. }
  405. return parts;
  406. }
  407. /// <inheritdoc />
  408. public IReadOnlyCollection<T> GetExports<T>(CreationDelegate defaultFunc, bool manageLifetime = true)
  409. {
  410. // Convert to list so this isn't executed for each iteration
  411. var parts = GetExportTypes<T>()
  412. .Select(i => defaultFunc(i))
  413. .Where(i => i != null)
  414. .Cast<T>()
  415. .ToList();
  416. if (manageLifetime)
  417. {
  418. lock (_disposableParts)
  419. {
  420. _disposableParts.AddRange(parts.OfType<IDisposable>());
  421. }
  422. }
  423. return parts;
  424. }
  425. /// <summary>
  426. /// Runs the startup tasks.
  427. /// </summary>
  428. /// <returns><see cref="Task" />.</returns>
  429. public async Task RunStartupTasksAsync(CancellationToken cancellationToken)
  430. {
  431. cancellationToken.ThrowIfCancellationRequested();
  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. cancellationToken.ThrowIfCancellationRequested();
  440. var stopWatch = new Stopwatch();
  441. stopWatch.Start();
  442. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  443. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  444. Logger.LogInformation("Core startup complete");
  445. CoreStartupHasCompleted = true;
  446. cancellationToken.ThrowIfCancellationRequested();
  447. stopWatch.Restart();
  448. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  449. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  450. stopWatch.Stop();
  451. }
  452. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  453. {
  454. foreach (var entryPoint in entryPoints)
  455. {
  456. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  457. {
  458. continue;
  459. }
  460. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  461. yield return entryPoint.RunAsync();
  462. }
  463. }
  464. /// <inheritdoc/>
  465. public void Init()
  466. {
  467. var networkConfiguration = ServerConfigurationManager.GetNetworkConfiguration();
  468. HttpPort = networkConfiguration.HttpServerPortNumber;
  469. HttpsPort = networkConfiguration.HttpsPortNumber;
  470. // Safeguard against invalid configuration
  471. if (HttpPort == HttpsPort)
  472. {
  473. HttpPort = NetworkConfiguration.DefaultHttpPort;
  474. HttpsPort = NetworkConfiguration.DefaultHttpsPort;
  475. }
  476. CertificateInfo = new CertificateInfo
  477. {
  478. Path = networkConfiguration.CertificatePath,
  479. Password = networkConfiguration.CertificatePassword
  480. };
  481. Certificate = GetCertificate(CertificateInfo);
  482. DiscoverTypes();
  483. RegisterServices();
  484. _pluginManager.RegisterServices(ServiceCollection);
  485. }
  486. /// <summary>
  487. /// Registers services/resources with the service collection that will be available via DI.
  488. /// </summary>
  489. protected virtual void RegisterServices()
  490. {
  491. ServiceCollection.AddSingleton(_startupOptions);
  492. ServiceCollection.AddMemoryCache();
  493. ServiceCollection.AddSingleton(ConfigurationManager);
  494. ServiceCollection.AddSingleton<IApplicationHost>(this);
  495. ServiceCollection.AddSingleton<IPluginManager>(_pluginManager);
  496. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  497. ServiceCollection.AddSingleton(_fileSystemManager);
  498. ServiceCollection.AddSingleton<TmdbClientManager>();
  499. ServiceCollection.AddSingleton(NetManager);
  500. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  501. ServiceCollection.AddSingleton(_xmlSerializer);
  502. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  503. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  504. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  505. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  506. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  507. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  508. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  509. ServiceCollection.AddSingleton(ServerConfigurationManager);
  510. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  511. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  512. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  513. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  514. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  515. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  516. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  517. ServiceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  518. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  519. ServiceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  520. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  521. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  522. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  523. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  524. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  525. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  526. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  527. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  528. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  529. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  530. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  531. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  532. ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  533. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  534. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  535. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  536. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  537. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  538. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  539. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  540. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  541. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  542. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  543. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  544. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  545. ServiceCollection.AddSingleton<LiveTvDtoService>();
  546. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  547. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  548. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  549. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  550. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  551. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  552. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  553. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  554. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  555. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  556. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  557. ServiceCollection.AddSingleton<EncodingHelper>();
  558. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  559. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  560. ServiceCollection.AddScoped<MediaInfoHelper>();
  561. ServiceCollection.AddScoped<AudioHelper>();
  562. ServiceCollection.AddScoped<DynamicHlsHelper>();
  563. }
  564. /// <summary>
  565. /// Create services registered with the service container that need to be initialized at application startup.
  566. /// </summary>
  567. /// <returns>A task representing the service initialization operation.</returns>
  568. public async Task InitializeServices()
  569. {
  570. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  571. await localizationManager.LoadAll().ConfigureAwait(false);
  572. _mediaEncoder = Resolve<IMediaEncoder>();
  573. _sessionManager = Resolve<ISessionManager>();
  574. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  575. SetStaticProperties();
  576. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  577. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  578. FindParts();
  579. }
  580. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  581. {
  582. // Distinct these to prevent users from reporting problems that aren't actually problems
  583. var commandLineArgs = Environment
  584. .GetCommandLineArgs()
  585. .Distinct();
  586. // Get all relevant environment variables
  587. var allEnvVars = Environment.GetEnvironmentVariables();
  588. var relevantEnvVars = new Dictionary<object, object>();
  589. foreach (var key in allEnvVars.Keys)
  590. {
  591. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  592. {
  593. relevantEnvVars.Add(key, allEnvVars[key]);
  594. }
  595. }
  596. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  597. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  598. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  599. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  600. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  601. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  602. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  603. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  604. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  605. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  606. }
  607. private X509Certificate2 GetCertificate(CertificateInfo info)
  608. {
  609. var certificateLocation = info?.Path;
  610. if (string.IsNullOrWhiteSpace(certificateLocation))
  611. {
  612. return null;
  613. }
  614. try
  615. {
  616. if (!File.Exists(certificateLocation))
  617. {
  618. return null;
  619. }
  620. // Don't use an empty string password
  621. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  622. var localCert = new X509Certificate2(certificateLocation, password, X509KeyStorageFlags.UserKeySet);
  623. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  624. if (!localCert.HasPrivateKey)
  625. {
  626. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  627. return null;
  628. }
  629. return localCert;
  630. }
  631. catch (Exception ex)
  632. {
  633. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  634. return null;
  635. }
  636. }
  637. /// <summary>
  638. /// Dirty hacks.
  639. /// </summary>
  640. private void SetStaticProperties()
  641. {
  642. // For now there's no real way to inject these properly
  643. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  644. BaseItem.ConfigurationManager = ServerConfigurationManager;
  645. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  646. BaseItem.ProviderManager = Resolve<IProviderManager>();
  647. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  648. BaseItem.ItemRepository = Resolve<IItemRepository>();
  649. BaseItem.FileSystem = _fileSystemManager;
  650. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  651. BaseItem.ChannelManager = Resolve<IChannelManager>();
  652. Video.LiveTvManager = Resolve<ILiveTvManager>();
  653. Folder.UserViewManager = Resolve<IUserViewManager>();
  654. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  655. UserView.CollectionManager = Resolve<ICollectionManager>();
  656. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  657. CollectionFolder.XmlSerializer = _xmlSerializer;
  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. }