ApplicationHost.cs 51 KB

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