ApplicationHost.cs 50 KB

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