ApplicationHost.cs 49 KB

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