ApplicationHost.cs 51 KB

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