ApplicationHost.cs 50 KB

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