ApplicationHost.cs 51 KB

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