ApplicationHost.cs 52 KB

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