ApplicationHost.cs 51 KB

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