ApplicationHost.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Net.Http;
  10. using System.Net.Sockets;
  11. using System.Reflection;
  12. using System.Runtime.InteropServices;
  13. using System.Security.Cryptography.X509Certificates;
  14. using System.Text;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using Emby.Dlna;
  18. using Emby.Dlna.Main;
  19. using Emby.Dlna.Ssdp;
  20. using Emby.Drawing;
  21. using Emby.Notifications;
  22. using Emby.Photos;
  23. using Emby.Server.Implementations.Archiving;
  24. using Emby.Server.Implementations.Channels;
  25. using Emby.Server.Implementations.Collections;
  26. using Emby.Server.Implementations.Configuration;
  27. using Emby.Server.Implementations.Cryptography;
  28. using Emby.Server.Implementations.Data;
  29. using Emby.Server.Implementations.Devices;
  30. using Emby.Server.Implementations.Dto;
  31. using Emby.Server.Implementations.HttpServer;
  32. using Emby.Server.Implementations.HttpServer.Security;
  33. using Emby.Server.Implementations.IO;
  34. using Emby.Server.Implementations.Library;
  35. using Emby.Server.Implementations.LiveTv;
  36. using Emby.Server.Implementations.Localization;
  37. using Emby.Server.Implementations.Net;
  38. using Emby.Server.Implementations.Playlists;
  39. using Emby.Server.Implementations.QuickConnect;
  40. using Emby.Server.Implementations.ScheduledTasks;
  41. using Emby.Server.Implementations.Security;
  42. using Emby.Server.Implementations.Serialization;
  43. using Emby.Server.Implementations.Session;
  44. using Emby.Server.Implementations.SyncPlay;
  45. using Emby.Server.Implementations.TV;
  46. using Emby.Server.Implementations.Updates;
  47. using Jellyfin.Api.Helpers;
  48. using MediaBrowser.Common;
  49. using MediaBrowser.Common.Configuration;
  50. using MediaBrowser.Common.Events;
  51. using MediaBrowser.Common.Json;
  52. using MediaBrowser.Common.Net;
  53. using MediaBrowser.Common.Plugins;
  54. using MediaBrowser.Common.Updates;
  55. using MediaBrowser.Controller;
  56. using MediaBrowser.Controller.Channels;
  57. using MediaBrowser.Controller.Chapters;
  58. using MediaBrowser.Controller.Collections;
  59. using MediaBrowser.Controller.Configuration;
  60. using MediaBrowser.Controller.Devices;
  61. using MediaBrowser.Controller.Dlna;
  62. using MediaBrowser.Controller.Drawing;
  63. using MediaBrowser.Controller.Dto;
  64. using MediaBrowser.Controller.Entities;
  65. using MediaBrowser.Controller.Library;
  66. using MediaBrowser.Controller.LiveTv;
  67. using MediaBrowser.Controller.MediaEncoding;
  68. using MediaBrowser.Controller.Net;
  69. using MediaBrowser.Controller.Notifications;
  70. using MediaBrowser.Controller.Persistence;
  71. using MediaBrowser.Controller.Playlists;
  72. using MediaBrowser.Controller.Plugins;
  73. using MediaBrowser.Controller.Providers;
  74. using MediaBrowser.Controller.QuickConnect;
  75. using MediaBrowser.Controller.Resolvers;
  76. using MediaBrowser.Controller.Security;
  77. using MediaBrowser.Controller.Session;
  78. using MediaBrowser.Controller.Sorting;
  79. using MediaBrowser.Controller.Subtitles;
  80. using MediaBrowser.Controller.SyncPlay;
  81. using MediaBrowser.Controller.TV;
  82. using MediaBrowser.LocalMetadata.Savers;
  83. using MediaBrowser.MediaEncoding.BdInfo;
  84. using MediaBrowser.Model.Configuration;
  85. using MediaBrowser.Model.Cryptography;
  86. using MediaBrowser.Model.Dlna;
  87. using MediaBrowser.Model.Globalization;
  88. using MediaBrowser.Model.IO;
  89. using MediaBrowser.Model.MediaInfo;
  90. using MediaBrowser.Model.Net;
  91. using MediaBrowser.Model.Serialization;
  92. using MediaBrowser.Model.System;
  93. using MediaBrowser.Model.Tasks;
  94. using MediaBrowser.Providers.Chapters;
  95. using MediaBrowser.Providers.Manager;
  96. using MediaBrowser.Providers.Plugins.TheTvdb;
  97. using MediaBrowser.Providers.Subtitles;
  98. using MediaBrowser.XbmcMetadata.Providers;
  99. using Microsoft.AspNetCore.Mvc;
  100. using Microsoft.Extensions.DependencyInjection;
  101. using Microsoft.Extensions.Logging;
  102. using Prometheus.DotNetRuntime;
  103. using OperatingSystem = MediaBrowser.Common.System.OperatingSystem;
  104. using WebSocketManager = Emby.Server.Implementations.HttpServer.WebSocketManager;
  105. namespace Emby.Server.Implementations
  106. {
  107. /// <summary>
  108. /// Class CompositionRoot.
  109. /// </summary>
  110. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  111. {
  112. /// <summary>
  113. /// The environment variable prefixes to log at server startup.
  114. /// </summary>
  115. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  116. private readonly IFileSystem _fileSystemManager;
  117. private readonly INetworkManager _networkManager;
  118. private readonly IXmlSerializer _xmlSerializer;
  119. private readonly IStartupOptions _startupOptions;
  120. private IMediaEncoder _mediaEncoder;
  121. private ISessionManager _sessionManager;
  122. private IHttpClientFactory _httpClientFactory;
  123. private IWebSocketManager _webSocketManager;
  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. /// Occurs when [has pending restart changed].
  152. /// </summary>
  153. public event EventHandler HasPendingRestartChanged;
  154. /// <summary>
  155. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  156. /// </summary>
  157. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  158. public bool HasPendingRestart { get; private set; }
  159. /// <inheritdoc />
  160. public bool IsShuttingDown { get; private set; }
  161. /// <summary>
  162. /// Gets the logger.
  163. /// </summary>
  164. protected ILogger<ApplicationHost> Logger { get; }
  165. protected IServiceCollection ServiceCollection { get; }
  166. private IPlugin[] _plugins;
  167. /// <summary>
  168. /// Gets the plugins.
  169. /// </summary>
  170. /// <value>The plugins.</value>
  171. public IReadOnlyList<IPlugin> Plugins => _plugins;
  172. /// <summary>
  173. /// Gets the logger factory.
  174. /// </summary>
  175. protected ILoggerFactory LoggerFactory { get; }
  176. /// <summary>
  177. /// Gets or sets the application paths.
  178. /// </summary>
  179. /// <value>The application paths.</value>
  180. protected IServerApplicationPaths ApplicationPaths { get; set; }
  181. /// <summary>
  182. /// Gets or sets all concrete types.
  183. /// </summary>
  184. /// <value>All concrete types.</value>
  185. private Type[] _allConcreteTypes;
  186. /// <summary>
  187. /// The disposable parts.
  188. /// </summary>
  189. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  190. /// <summary>
  191. /// Gets the configuration manager.
  192. /// </summary>
  193. /// <value>The configuration manager.</value>
  194. protected IConfigurationManager ConfigurationManager { get; set; }
  195. /// <summary>
  196. /// Gets or sets the service provider.
  197. /// </summary>
  198. public IServiceProvider ServiceProvider { get; set; }
  199. /// <summary>
  200. /// Gets the http port for the webhost.
  201. /// </summary>
  202. public int HttpPort { get; private set; }
  203. /// <summary>
  204. /// Gets the https port for the webhost.
  205. /// </summary>
  206. public int HttpsPort { get; private set; }
  207. /// <summary>
  208. /// Gets the server configuration manager.
  209. /// </summary>
  210. /// <value>The server configuration manager.</value>
  211. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  212. /// <summary>
  213. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  214. /// </summary>
  215. public ApplicationHost(
  216. IServerApplicationPaths applicationPaths,
  217. ILoggerFactory loggerFactory,
  218. IStartupOptions options,
  219. IFileSystem fileSystem,
  220. INetworkManager networkManager,
  221. IServiceCollection serviceCollection)
  222. {
  223. _xmlSerializer = new MyXmlSerializer();
  224. ServiceCollection = serviceCollection;
  225. _networkManager = networkManager;
  226. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  227. ApplicationPaths = applicationPaths;
  228. LoggerFactory = loggerFactory;
  229. _fileSystemManager = fileSystem;
  230. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  231. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  232. _startupOptions = options;
  233. // Initialize runtime stat collection
  234. if (ServerConfigurationManager.Configuration.EnableMetrics)
  235. {
  236. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  237. }
  238. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  239. _networkManager.NetworkChanged += OnNetworkChanged;
  240. CertificateInfo = new CertificateInfo
  241. {
  242. Path = ServerConfigurationManager.Configuration.CertificatePath,
  243. Password = ServerConfigurationManager.Configuration.CertificatePassword
  244. };
  245. Certificate = GetCertificate(CertificateInfo);
  246. ApplicationVersion = typeof(ApplicationHost).Assembly.GetName().Version;
  247. ApplicationVersionString = ApplicationVersion.ToString(3);
  248. ApplicationUserAgent = Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  249. }
  250. public string ExpandVirtualPath(string path)
  251. {
  252. var appPaths = ApplicationPaths;
  253. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  254. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  255. }
  256. public string ReverseVirtualPath(string path)
  257. {
  258. var appPaths = ApplicationPaths;
  259. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  260. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  261. }
  262. private string[] GetConfiguredLocalSubnets()
  263. {
  264. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  265. }
  266. private void OnNetworkChanged(object sender, EventArgs e)
  267. {
  268. _validAddressResults.Clear();
  269. }
  270. /// <inheritdoc />
  271. public Version ApplicationVersion { get; }
  272. /// <inheritdoc />
  273. public string ApplicationVersionString { get; }
  274. /// <summary>
  275. /// Gets the current application user agent.
  276. /// </summary>
  277. /// <value>The application user agent.</value>
  278. public string ApplicationUserAgent { get; }
  279. /// <summary>
  280. /// Gets the email address for use within a comment section of a user agent field.
  281. /// Presently used to provide contact information to MusicBrainz service.
  282. /// </summary>
  283. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  284. /// <summary>
  285. /// Gets the current application name.
  286. /// </summary>
  287. /// <value>The application name.</value>
  288. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  289. private DeviceId _deviceId;
  290. public string SystemId
  291. {
  292. get
  293. {
  294. if (_deviceId == null)
  295. {
  296. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  297. }
  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. try
  325. {
  326. Logger.LogDebug("Creating instance of {Type}", type);
  327. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  328. }
  329. catch (Exception ex)
  330. {
  331. Logger.LogError(ex, "Error creating {Type}", type);
  332. return null;
  333. }
  334. }
  335. /// <summary>
  336. /// Resolves this instance.
  337. /// </summary>
  338. /// <typeparam name="T">The type</typeparam>
  339. /// <returns>``0.</returns>
  340. public T Resolve<T>() => ServiceProvider.GetService<T>();
  341. /// <summary>
  342. /// Gets the export types.
  343. /// </summary>
  344. /// <typeparam name="T">The type.</typeparam>
  345. /// <returns>IEnumerable{Type}.</returns>
  346. public IEnumerable<Type> GetExportTypes<T>()
  347. {
  348. var currentType = typeof(T);
  349. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  350. }
  351. /// <inheritdoc />
  352. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  353. {
  354. // Convert to list so this isn't executed for each iteration
  355. var parts = GetExportTypes<T>()
  356. .Select(CreateInstanceSafe)
  357. .Where(i => i != null)
  358. .Cast<T>()
  359. .ToList();
  360. if (manageLifetime)
  361. {
  362. lock (_disposableParts)
  363. {
  364. _disposableParts.AddRange(parts.OfType<IDisposable>());
  365. }
  366. }
  367. return parts;
  368. }
  369. /// <summary>
  370. /// Runs the startup tasks.
  371. /// </summary>
  372. /// <returns><see cref="Task" />.</returns>
  373. public async Task RunStartupTasksAsync()
  374. {
  375. Logger.LogInformation("Running startup tasks");
  376. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  377. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  378. _mediaEncoder.SetFFmpegPath();
  379. Logger.LogInformation("ServerId: {0}", SystemId);
  380. var entryPoints = GetExports<IServerEntryPoint>();
  381. var stopWatch = new Stopwatch();
  382. stopWatch.Start();
  383. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  384. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  385. Logger.LogInformation("Core startup complete");
  386. CoreStartupHasCompleted = true;
  387. stopWatch.Restart();
  388. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  389. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  390. stopWatch.Stop();
  391. }
  392. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  393. {
  394. foreach (var entryPoint in entryPoints)
  395. {
  396. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  397. {
  398. continue;
  399. }
  400. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  401. yield return entryPoint.RunAsync();
  402. }
  403. }
  404. /// <inheritdoc/>
  405. public void Init()
  406. {
  407. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  408. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  409. // Safeguard against invalid configuration
  410. if (HttpPort == HttpsPort)
  411. {
  412. HttpPort = ServerConfiguration.DefaultHttpPort;
  413. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  414. }
  415. if (Plugins != null)
  416. {
  417. var pluginBuilder = new StringBuilder();
  418. foreach (var plugin in Plugins)
  419. {
  420. pluginBuilder.Append(plugin.Name)
  421. .Append(' ')
  422. .Append(plugin.Version)
  423. .AppendLine();
  424. }
  425. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  426. }
  427. DiscoverTypes();
  428. RegisterServices();
  429. }
  430. /// <summary>
  431. /// Registers services/resources with the service collection that will be available via DI.
  432. /// </summary>
  433. protected virtual void RegisterServices()
  434. {
  435. ServiceCollection.AddSingleton(_startupOptions);
  436. ServiceCollection.AddMemoryCache();
  437. ServiceCollection.AddSingleton(ConfigurationManager);
  438. ServiceCollection.AddSingleton<IApplicationHost>(this);
  439. ServiceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  440. ServiceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  441. ServiceCollection.AddSingleton(_fileSystemManager);
  442. ServiceCollection.AddSingleton<TvdbClientManager>();
  443. ServiceCollection.AddSingleton(_networkManager);
  444. ServiceCollection.AddSingleton<IIsoManager, IsoManager>();
  445. ServiceCollection.AddSingleton<ITaskManager, TaskManager>();
  446. ServiceCollection.AddSingleton(_xmlSerializer);
  447. ServiceCollection.AddSingleton<IStreamHelper, StreamHelper>();
  448. ServiceCollection.AddSingleton<ICryptoProvider, CryptographyProvider>();
  449. ServiceCollection.AddSingleton<ISocketFactory, SocketFactory>();
  450. ServiceCollection.AddSingleton<IInstallationManager, InstallationManager>();
  451. ServiceCollection.AddSingleton<IZipClient, ZipClient>();
  452. ServiceCollection.AddSingleton<IServerApplicationHost>(this);
  453. ServiceCollection.AddSingleton<IServerApplicationPaths>(ApplicationPaths);
  454. ServiceCollection.AddSingleton(ServerConfigurationManager);
  455. ServiceCollection.AddSingleton<ILocalizationManager, LocalizationManager>();
  456. ServiceCollection.AddSingleton<IBlurayExaminer, BdInfoExaminer>();
  457. ServiceCollection.AddSingleton<IUserDataRepository, SqliteUserDataRepository>();
  458. ServiceCollection.AddSingleton<IUserDataManager, UserDataManager>();
  459. ServiceCollection.AddSingleton<IItemRepository, SqliteItemRepository>();
  460. ServiceCollection.AddSingleton<IAuthenticationRepository, AuthenticationRepository>();
  461. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  462. ServiceCollection.AddTransient(provider => new Lazy<IDtoService>(provider.GetRequiredService<IDtoService>));
  463. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  464. ServiceCollection.AddTransient(provider => new Lazy<EncodingHelper>(provider.GetRequiredService<EncodingHelper>));
  465. ServiceCollection.AddSingleton<IMediaEncoder, MediaBrowser.MediaEncoding.Encoder.MediaEncoder>();
  466. // TODO: Refactor to eliminate the circular dependencies here so that Lazy<T> isn't required
  467. ServiceCollection.AddTransient(provider => new Lazy<ILibraryMonitor>(provider.GetRequiredService<ILibraryMonitor>));
  468. ServiceCollection.AddTransient(provider => new Lazy<IProviderManager>(provider.GetRequiredService<IProviderManager>));
  469. ServiceCollection.AddTransient(provider => new Lazy<IUserViewManager>(provider.GetRequiredService<IUserViewManager>));
  470. ServiceCollection.AddSingleton<ILibraryManager, LibraryManager>();
  471. ServiceCollection.AddSingleton<IMusicManager, MusicManager>();
  472. ServiceCollection.AddSingleton<ILibraryMonitor, LibraryMonitor>();
  473. ServiceCollection.AddSingleton<ISearchEngine, SearchEngine>();
  474. ServiceCollection.AddSingleton<IWebSocketManager, WebSocketManager>();
  475. ServiceCollection.AddSingleton<IImageProcessor, ImageProcessor>();
  476. ServiceCollection.AddSingleton<ITVSeriesManager, TVSeriesManager>();
  477. ServiceCollection.AddSingleton<IDeviceManager, DeviceManager>();
  478. ServiceCollection.AddSingleton<IMediaSourceManager, MediaSourceManager>();
  479. ServiceCollection.AddSingleton<ISubtitleManager, SubtitleManager>();
  480. ServiceCollection.AddSingleton<IProviderManager, ProviderManager>();
  481. // TODO: Refactor to eliminate the circular dependency here so that Lazy<T> isn't required
  482. ServiceCollection.AddTransient(provider => new Lazy<ILiveTvManager>(provider.GetRequiredService<ILiveTvManager>));
  483. ServiceCollection.AddSingleton<IDtoService, DtoService>();
  484. ServiceCollection.AddSingleton<IChannelManager, ChannelManager>();
  485. ServiceCollection.AddSingleton<ISessionManager, SessionManager>();
  486. ServiceCollection.AddSingleton<IDlnaManager, DlnaManager>();
  487. ServiceCollection.AddSingleton<ICollectionManager, CollectionManager>();
  488. ServiceCollection.AddSingleton<IPlaylistManager, PlaylistManager>();
  489. ServiceCollection.AddSingleton<ISyncPlayManager, SyncPlayManager>();
  490. ServiceCollection.AddSingleton<LiveTvDtoService>();
  491. ServiceCollection.AddSingleton<ILiveTvManager, LiveTvManager>();
  492. ServiceCollection.AddSingleton<IUserViewManager, UserViewManager>();
  493. ServiceCollection.AddSingleton<INotificationManager, NotificationManager>();
  494. ServiceCollection.AddSingleton<IDeviceDiscovery, DeviceDiscovery>();
  495. ServiceCollection.AddSingleton<IChapterManager, ChapterManager>();
  496. ServiceCollection.AddSingleton<IEncodingManager, MediaEncoder.EncodingManager>();
  497. ServiceCollection.AddSingleton<IAuthorizationContext, AuthorizationContext>();
  498. ServiceCollection.AddSingleton<ISessionContext, SessionContext>();
  499. ServiceCollection.AddSingleton<IAuthService, AuthService>();
  500. ServiceCollection.AddSingleton<IQuickConnect, QuickConnectManager>();
  501. ServiceCollection.AddSingleton<ISubtitleEncoder, MediaBrowser.MediaEncoding.Subtitles.SubtitleEncoder>();
  502. ServiceCollection.AddSingleton<IResourceFileManager, ResourceFileManager>();
  503. ServiceCollection.AddSingleton<EncodingHelper>();
  504. ServiceCollection.AddSingleton<IAttachmentExtractor, MediaBrowser.MediaEncoding.Attachments.AttachmentExtractor>();
  505. ServiceCollection.AddSingleton<TranscodingJobHelper>();
  506. ServiceCollection.AddScoped<MediaInfoHelper>();
  507. ServiceCollection.AddScoped<AudioHelper>();
  508. ServiceCollection.AddScoped<DynamicHlsHelper>();
  509. }
  510. /// <summary>
  511. /// Create services registered with the service container that need to be initialized at application startup.
  512. /// </summary>
  513. /// <returns>A task representing the service initialization operation.</returns>
  514. public async Task InitializeServices()
  515. {
  516. var localizationManager = (LocalizationManager)Resolve<ILocalizationManager>();
  517. await localizationManager.LoadAll().ConfigureAwait(false);
  518. _mediaEncoder = Resolve<IMediaEncoder>();
  519. _sessionManager = Resolve<ISessionManager>();
  520. _httpClientFactory = Resolve<IHttpClientFactory>();
  521. _webSocketManager = Resolve<IWebSocketManager>();
  522. ((AuthenticationRepository)Resolve<IAuthenticationRepository>()).Initialize();
  523. SetStaticProperties();
  524. var userDataRepo = (SqliteUserDataRepository)Resolve<IUserDataRepository>();
  525. ((SqliteItemRepository)Resolve<IItemRepository>()).Initialize(userDataRepo, Resolve<IUserManager>());
  526. FindParts();
  527. }
  528. public static void LogEnvironmentInfo(ILogger logger, IApplicationPaths appPaths)
  529. {
  530. // Distinct these to prevent users from reporting problems that aren't actually problems
  531. var commandLineArgs = Environment
  532. .GetCommandLineArgs()
  533. .Distinct();
  534. // Get all relevant environment variables
  535. var allEnvVars = Environment.GetEnvironmentVariables();
  536. var relevantEnvVars = new Dictionary<object, object>();
  537. foreach (var key in allEnvVars.Keys)
  538. {
  539. if (_relevantEnvVarPrefixes.Any(prefix => key.ToString().StartsWith(prefix, StringComparison.OrdinalIgnoreCase)))
  540. {
  541. relevantEnvVars.Add(key, allEnvVars[key]);
  542. }
  543. }
  544. logger.LogInformation("Environment Variables: {EnvVars}", relevantEnvVars);
  545. logger.LogInformation("Arguments: {Args}", commandLineArgs);
  546. logger.LogInformation("Operating system: {OS}", OperatingSystem.Name);
  547. logger.LogInformation("Architecture: {Architecture}", RuntimeInformation.OSArchitecture);
  548. logger.LogInformation("64-Bit Process: {Is64Bit}", Environment.Is64BitProcess);
  549. logger.LogInformation("User Interactive: {IsUserInteractive}", Environment.UserInteractive);
  550. logger.LogInformation("Processor count: {ProcessorCount}", Environment.ProcessorCount);
  551. logger.LogInformation("Program data path: {ProgramDataPath}", appPaths.ProgramDataPath);
  552. logger.LogInformation("Web resources path: {WebPath}", appPaths.WebPath);
  553. logger.LogInformation("Application directory: {ApplicationPath}", appPaths.ProgramSystemPath);
  554. }
  555. private X509Certificate2 GetCertificate(CertificateInfo info)
  556. {
  557. var certificateLocation = info?.Path;
  558. if (string.IsNullOrWhiteSpace(certificateLocation))
  559. {
  560. return null;
  561. }
  562. try
  563. {
  564. if (!File.Exists(certificateLocation))
  565. {
  566. return null;
  567. }
  568. // Don't use an empty string password
  569. var password = string.IsNullOrWhiteSpace(info.Password) ? null : info.Password;
  570. var localCert = new X509Certificate2(certificateLocation, password);
  571. // localCert.PrivateKey = PrivateKey.CreateFromFile(pvk_file).RSA;
  572. if (!localCert.HasPrivateKey)
  573. {
  574. Logger.LogError("No private key included in SSL cert {CertificateLocation}.", certificateLocation);
  575. return null;
  576. }
  577. return localCert;
  578. }
  579. catch (Exception ex)
  580. {
  581. Logger.LogError(ex, "Error loading cert from {CertificateLocation}", certificateLocation);
  582. return null;
  583. }
  584. }
  585. /// <summary>
  586. /// Dirty hacks.
  587. /// </summary>
  588. private void SetStaticProperties()
  589. {
  590. // For now there's no real way to inject these properly
  591. BaseItem.Logger = Resolve<ILogger<BaseItem>>();
  592. BaseItem.ConfigurationManager = ServerConfigurationManager;
  593. BaseItem.LibraryManager = Resolve<ILibraryManager>();
  594. BaseItem.ProviderManager = Resolve<IProviderManager>();
  595. BaseItem.LocalizationManager = Resolve<ILocalizationManager>();
  596. BaseItem.ItemRepository = Resolve<IItemRepository>();
  597. BaseItem.FileSystem = _fileSystemManager;
  598. BaseItem.UserDataManager = Resolve<IUserDataManager>();
  599. BaseItem.ChannelManager = Resolve<IChannelManager>();
  600. Video.LiveTvManager = Resolve<ILiveTvManager>();
  601. Folder.UserViewManager = Resolve<IUserViewManager>();
  602. UserView.TVSeriesManager = Resolve<ITVSeriesManager>();
  603. UserView.CollectionManager = Resolve<ICollectionManager>();
  604. BaseItem.MediaSourceManager = Resolve<IMediaSourceManager>();
  605. CollectionFolder.XmlSerializer = _xmlSerializer;
  606. CollectionFolder.JsonSerializer = Resolve<IJsonSerializer>();
  607. CollectionFolder.ApplicationHost = this;
  608. }
  609. /// <summary>
  610. /// Finds plugin components and register them with the appropriate services.
  611. /// </summary>
  612. private void FindParts()
  613. {
  614. if (!ServerConfigurationManager.Configuration.IsPortAuthorized)
  615. {
  616. ServerConfigurationManager.Configuration.IsPortAuthorized = true;
  617. ConfigurationManager.SaveConfiguration();
  618. }
  619. ConfigurationManager.AddParts(GetExports<IConfigurationFactory>());
  620. _plugins = GetExports<IPlugin>()
  621. .Select(LoadPlugin)
  622. .Where(i => i != null)
  623. .ToArray();
  624. _urlPrefixes = GetUrlPrefixes().ToArray();
  625. _webSocketManager.Init(GetExports<IWebSocketListener>());
  626. Resolve<ILibraryManager>().AddParts(
  627. GetExports<IResolverIgnoreRule>(),
  628. GetExports<IItemResolver>(),
  629. GetExports<IIntroProvider>(),
  630. GetExports<IBaseItemComparer>(),
  631. GetExports<ILibraryPostScanTask>());
  632. Resolve<IProviderManager>().AddParts(
  633. GetExports<IImageProvider>(),
  634. GetExports<IMetadataService>(),
  635. GetExports<IMetadataProvider>(),
  636. GetExports<IMetadataSaver>(),
  637. GetExports<IExternalId>());
  638. Resolve<ILiveTvManager>().AddParts(GetExports<ILiveTvService>(), GetExports<ITunerHost>(), GetExports<IListingsProvider>());
  639. Resolve<ISubtitleManager>().AddParts(GetExports<ISubtitleProvider>());
  640. Resolve<IChannelManager>().AddParts(GetExports<IChannel>());
  641. Resolve<IMediaSourceManager>().AddParts(GetExports<IMediaSourceProvider>());
  642. Resolve<INotificationManager>().AddParts(GetExports<INotificationService>(), GetExports<INotificationTypeFactory>());
  643. Resolve<IIsoManager>().AddParts(GetExports<IIsoMounter>());
  644. }
  645. private IPlugin LoadPlugin(IPlugin plugin)
  646. {
  647. try
  648. {
  649. if (plugin is IPluginAssembly assemblyPlugin)
  650. {
  651. var assembly = plugin.GetType().Assembly;
  652. var assemblyName = assembly.GetName();
  653. var assemblyFilePath = assembly.Location;
  654. var dataFolderPath = Path.Combine(ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(assemblyFilePath));
  655. assemblyPlugin.SetAttributes(assemblyFilePath, dataFolderPath, assemblyName.Version);
  656. try
  657. {
  658. var idAttributes = assembly.GetCustomAttributes(typeof(GuidAttribute), true);
  659. if (idAttributes.Length > 0)
  660. {
  661. var attribute = (GuidAttribute)idAttributes[0];
  662. var assemblyId = new Guid(attribute.Value);
  663. assemblyPlugin.SetId(assemblyId);
  664. }
  665. }
  666. catch (Exception ex)
  667. {
  668. Logger.LogError(ex, "Error getting plugin Id from {PluginName}.", plugin.GetType().FullName);
  669. }
  670. }
  671. if (plugin is IHasPluginConfiguration hasPluginConfiguration)
  672. {
  673. hasPluginConfiguration.SetStartupInfo(s => Directory.CreateDirectory(s));
  674. }
  675. plugin.RegisterServices(ServiceCollection);
  676. }
  677. catch (Exception ex)
  678. {
  679. Logger.LogError(ex, "Error loading plugin {PluginName}", plugin.GetType().FullName);
  680. return null;
  681. }
  682. return plugin;
  683. }
  684. /// <summary>
  685. /// Discovers the types.
  686. /// </summary>
  687. protected void DiscoverTypes()
  688. {
  689. Logger.LogInformation("Loading assemblies");
  690. _allConcreteTypes = GetTypes(GetComposablePartAssemblies()).ToArray();
  691. }
  692. private IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
  693. {
  694. foreach (var ass in assemblies)
  695. {
  696. Type[] exportedTypes;
  697. try
  698. {
  699. exportedTypes = ass.GetExportedTypes();
  700. }
  701. catch (FileNotFoundException ex)
  702. {
  703. Logger.LogError(ex, "Error getting exported types from {Assembly}", ass.FullName);
  704. continue;
  705. }
  706. catch (TypeLoadException ex)
  707. {
  708. Logger.LogError(ex, "Error loading types from {Assembly}.", ass.FullName);
  709. continue;
  710. }
  711. foreach (Type type in exportedTypes)
  712. {
  713. if (type.IsClass && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
  714. {
  715. yield return type;
  716. }
  717. }
  718. }
  719. }
  720. private CertificateInfo CertificateInfo { get; set; }
  721. public X509Certificate2 Certificate { get; private set; }
  722. private IEnumerable<string> GetUrlPrefixes()
  723. {
  724. var hosts = new[] { "+" };
  725. return hosts.SelectMany(i =>
  726. {
  727. var prefixes = new List<string>
  728. {
  729. "http://" + i + ":" + HttpPort + "/"
  730. };
  731. if (CertificateInfo != null)
  732. {
  733. prefixes.Add("https://" + i + ":" + HttpsPort + "/");
  734. }
  735. return prefixes;
  736. });
  737. }
  738. /// <summary>
  739. /// Called when [configuration updated].
  740. /// </summary>
  741. /// <param name="sender">The sender.</param>
  742. /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  743. protected void OnConfigurationUpdated(object sender, EventArgs e)
  744. {
  745. var requiresRestart = false;
  746. // Don't do anything if these haven't been set yet
  747. if (HttpPort != 0 && HttpsPort != 0)
  748. {
  749. // Need to restart if ports have changed
  750. if (ServerConfigurationManager.Configuration.HttpServerPortNumber != HttpPort ||
  751. ServerConfigurationManager.Configuration.HttpsPortNumber != HttpsPort)
  752. {
  753. if (ServerConfigurationManager.Configuration.IsPortAuthorized)
  754. {
  755. ServerConfigurationManager.Configuration.IsPortAuthorized = false;
  756. ServerConfigurationManager.SaveConfiguration();
  757. requiresRestart = true;
  758. }
  759. }
  760. }
  761. if (!_urlPrefixes.SequenceEqual(GetUrlPrefixes(), StringComparer.OrdinalIgnoreCase))
  762. {
  763. requiresRestart = true;
  764. }
  765. var currentCertPath = CertificateInfo?.Path;
  766. var newCertPath = ServerConfigurationManager.Configuration.CertificatePath;
  767. if (!string.Equals(currentCertPath, newCertPath, StringComparison.OrdinalIgnoreCase))
  768. {
  769. requiresRestart = true;
  770. }
  771. if (requiresRestart)
  772. {
  773. Logger.LogInformation("App needs to be restarted due to configuration change.");
  774. NotifyPendingRestart();
  775. }
  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. if (Directory.Exists(ApplicationPaths.PluginsPath))
  826. {
  827. foreach (var file in Directory.EnumerateFiles(ApplicationPaths.PluginsPath, "*.dll", SearchOption.AllDirectories))
  828. {
  829. Assembly plugAss;
  830. try
  831. {
  832. plugAss = Assembly.LoadFrom(file);
  833. }
  834. catch (FileLoadException ex)
  835. {
  836. Logger.LogError(ex, "Failed to load assembly {Path}", file);
  837. continue;
  838. }
  839. Logger.LogInformation("Loaded assembly {Assembly} from {Path}", plugAss.FullName, file);
  840. yield return plugAss;
  841. }
  842. }
  843. // Include composable parts in the Model assembly
  844. yield return typeof(SystemInfo).Assembly;
  845. // Include composable parts in the Common assembly
  846. yield return typeof(IApplicationHost).Assembly;
  847. // Include composable parts in the Controller assembly
  848. yield return typeof(IServerApplicationHost).Assembly;
  849. // Include composable parts in the Providers assembly
  850. yield return typeof(ProviderUtils).Assembly;
  851. // Include composable parts in the Photos assembly
  852. yield return typeof(PhotoProvider).Assembly;
  853. // Emby.Server implementations
  854. yield return typeof(InstallationManager).Assembly;
  855. // MediaEncoding
  856. yield return typeof(MediaBrowser.MediaEncoding.Encoder.MediaEncoder).Assembly;
  857. // Dlna
  858. yield return typeof(DlnaEntryPoint).Assembly;
  859. // Local metadata
  860. yield return typeof(BoxSetXmlSaver).Assembly;
  861. // Notifications
  862. yield return typeof(NotificationManager).Assembly;
  863. // Xbmc
  864. yield return typeof(ArtistNfoProvider).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="cancellationToken">The cancellation token.</param>
  875. /// <returns>SystemInfo.</returns>
  876. public async Task<SystemInfo> GetSystemInfo(CancellationToken cancellationToken)
  877. {
  878. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  879. var transcodingTempPath = ConfigurationManager.GetTranscodePath();
  880. return new SystemInfo
  881. {
  882. HasPendingRestart = HasPendingRestart,
  883. IsShuttingDown = IsShuttingDown,
  884. Version = ApplicationVersionString,
  885. WebSocketPortNumber = HttpPort,
  886. CompletedInstallations = Resolve<IInstallationManager>().CompletedInstallations.ToArray(),
  887. Id = SystemId,
  888. ProgramDataPath = ApplicationPaths.ProgramDataPath,
  889. WebPath = ApplicationPaths.WebPath,
  890. LogPath = ApplicationPaths.LogDirectoryPath,
  891. ItemsByNamePath = ApplicationPaths.InternalMetadataPath,
  892. InternalMetadataPath = ApplicationPaths.InternalMetadataPath,
  893. CachePath = ApplicationPaths.CachePath,
  894. OperatingSystem = OperatingSystem.Id.ToString(),
  895. OperatingSystemDisplayName = OperatingSystem.Name,
  896. CanSelfRestart = CanSelfRestart,
  897. CanLaunchWebBrowser = CanLaunchWebBrowser,
  898. HasUpdateAvailable = HasUpdateAvailable,
  899. TranscodingTempPath = transcodingTempPath,
  900. ServerName = FriendlyName,
  901. LocalAddress = localAddress,
  902. SupportsLibraryMonitor = true,
  903. EncoderLocation = _mediaEncoder.EncoderLocation,
  904. SystemArchitecture = RuntimeInformation.OSArchitecture,
  905. PackageName = _startupOptions.PackageName
  906. };
  907. }
  908. public IEnumerable<WakeOnLanInfo> GetWakeOnLanInfo()
  909. => _networkManager.GetMacAddresses()
  910. .Select(i => new WakeOnLanInfo(i))
  911. .ToList();
  912. public async Task<PublicSystemInfo> GetPublicSystemInfo(CancellationToken cancellationToken)
  913. {
  914. var localAddress = await GetLocalApiUrl(cancellationToken).ConfigureAwait(false);
  915. return new PublicSystemInfo
  916. {
  917. Version = ApplicationVersionString,
  918. ProductName = ApplicationProductName,
  919. Id = SystemId,
  920. OperatingSystem = OperatingSystem.Id.ToString(),
  921. ServerName = FriendlyName,
  922. LocalAddress = localAddress
  923. };
  924. }
  925. /// <inheritdoc/>
  926. public bool ListenWithHttps => Certificate != null && ServerConfigurationManager.Configuration.EnableHttps;
  927. /// <inheritdoc/>
  928. public async Task<string> GetLocalApiUrl(CancellationToken cancellationToken)
  929. {
  930. try
  931. {
  932. // Return the first matched address, if found, or the first known local address
  933. var addresses = await GetLocalIpAddressesInternal(false, 1, cancellationToken).ConfigureAwait(false);
  934. if (addresses.Count == 0)
  935. {
  936. return null;
  937. }
  938. return GetLocalApiUrl(addresses[0]);
  939. }
  940. catch (Exception ex)
  941. {
  942. Logger.LogError(ex, "Error getting local Ip address information");
  943. }
  944. return null;
  945. }
  946. /// <summary>
  947. /// Removes the scope id from IPv6 addresses.
  948. /// </summary>
  949. /// <param name="address">The IPv6 address.</param>
  950. /// <returns>The IPv6 address without the scope id.</returns>
  951. private ReadOnlySpan<char> RemoveScopeId(ReadOnlySpan<char> address)
  952. {
  953. var index = address.IndexOf('%');
  954. if (index == -1)
  955. {
  956. return address;
  957. }
  958. return address.Slice(0, index);
  959. }
  960. /// <inheritdoc />
  961. public string GetLocalApiUrl(IPAddress ipAddress)
  962. {
  963. if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
  964. {
  965. var str = RemoveScopeId(ipAddress.ToString());
  966. Span<char> span = new char[str.Length + 2];
  967. span[0] = '[';
  968. str.CopyTo(span.Slice(1));
  969. span[^1] = ']';
  970. return GetLocalApiUrl(span);
  971. }
  972. return GetLocalApiUrl(ipAddress.ToString());
  973. }
  974. /// <inheritdoc/>
  975. public string GetLoopbackHttpApiUrl()
  976. {
  977. return GetLocalApiUrl("127.0.0.1", Uri.UriSchemeHttp, HttpPort);
  978. }
  979. /// <inheritdoc/>
  980. public string GetLocalApiUrl(ReadOnlySpan<char> host, string scheme = null, int? port = null)
  981. {
  982. // NOTE: If no BaseUrl is set then UriBuilder appends a trailing slash, but if there is no BaseUrl it does
  983. // not. For consistency, always trim the trailing slash.
  984. return new UriBuilder
  985. {
  986. Scheme = scheme ?? (ListenWithHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp),
  987. Host = host.ToString(),
  988. Port = port ?? (ListenWithHttps ? HttpsPort : HttpPort),
  989. Path = ServerConfigurationManager.Configuration.BaseUrl
  990. }.ToString().TrimEnd('/');
  991. }
  992. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  993. {
  994. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  995. }
  996. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  997. {
  998. var addresses = ServerConfigurationManager
  999. .Configuration
  1000. .LocalNetworkAddresses
  1001. .Select(x => NormalizeConfiguredLocalAddress(x))
  1002. .Where(i => i != null)
  1003. .ToList();
  1004. if (addresses.Count == 0)
  1005. {
  1006. addresses.AddRange(_networkManager.GetLocalIpAddresses());
  1007. }
  1008. var resultList = new List<IPAddress>();
  1009. foreach (var address in addresses)
  1010. {
  1011. if (!allowLoopback)
  1012. {
  1013. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1014. {
  1015. continue;
  1016. }
  1017. }
  1018. if (await IsLocalIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false))
  1019. {
  1020. resultList.Add(address);
  1021. if (limit > 0 && resultList.Count >= limit)
  1022. {
  1023. return resultList;
  1024. }
  1025. }
  1026. }
  1027. return resultList;
  1028. }
  1029. public IPAddress NormalizeConfiguredLocalAddress(ReadOnlySpan<char> address)
  1030. {
  1031. var index = address.Trim('/').IndexOf('/');
  1032. if (index != -1)
  1033. {
  1034. address = address.Slice(index + 1);
  1035. }
  1036. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1037. {
  1038. return result;
  1039. }
  1040. return null;
  1041. }
  1042. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1043. private async Task<bool> IsLocalIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1044. {
  1045. if (address.Equals(IPAddress.Loopback)
  1046. || address.Equals(IPAddress.IPv6Loopback))
  1047. {
  1048. return true;
  1049. }
  1050. var apiUrl = GetLocalApiUrl(address) + "/system/ping";
  1051. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1052. {
  1053. return cachedResult;
  1054. }
  1055. try
  1056. {
  1057. using var request = new HttpRequestMessage(HttpMethod.Post, apiUrl);
  1058. using var response = await _httpClientFactory.CreateClient(NamedClient.Default)
  1059. .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
  1060. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  1061. var result = await System.Text.Json.JsonSerializer.DeserializeAsync<string>(stream, JsonDefaults.GetOptions(), cancellationToken).ConfigureAwait(false);
  1062. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1063. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1064. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1065. return valid;
  1066. }
  1067. catch (OperationCanceledException)
  1068. {
  1069. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1070. throw;
  1071. }
  1072. catch (Exception ex)
  1073. {
  1074. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1075. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1076. return false;
  1077. }
  1078. }
  1079. public string FriendlyName =>
  1080. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1081. ? Environment.MachineName
  1082. : ServerConfigurationManager.Configuration.ServerName;
  1083. /// <summary>
  1084. /// Shuts down.
  1085. /// </summary>
  1086. public async Task Shutdown()
  1087. {
  1088. if (IsShuttingDown)
  1089. {
  1090. return;
  1091. }
  1092. IsShuttingDown = true;
  1093. try
  1094. {
  1095. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1096. }
  1097. catch (Exception ex)
  1098. {
  1099. Logger.LogError(ex, "Error sending server shutdown notification");
  1100. }
  1101. ShutdownInternal();
  1102. }
  1103. protected abstract void ShutdownInternal();
  1104. public event EventHandler HasUpdateAvailableChanged;
  1105. private bool _hasUpdateAvailable;
  1106. public bool HasUpdateAvailable
  1107. {
  1108. get => _hasUpdateAvailable;
  1109. set
  1110. {
  1111. var fireEvent = value && !_hasUpdateAvailable;
  1112. _hasUpdateAvailable = value;
  1113. if (fireEvent)
  1114. {
  1115. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1116. }
  1117. }
  1118. }
  1119. /// <summary>
  1120. /// Removes the plugin.
  1121. /// </summary>
  1122. /// <param name="plugin">The plugin.</param>
  1123. public void RemovePlugin(IPlugin plugin)
  1124. {
  1125. var list = _plugins.ToList();
  1126. list.Remove(plugin);
  1127. _plugins = list.ToArray();
  1128. }
  1129. public IEnumerable<Assembly> GetApiPluginAssemblies()
  1130. {
  1131. var assemblies = _allConcreteTypes
  1132. .Where(i => typeof(ControllerBase).IsAssignableFrom(i))
  1133. .Select(i => i.Assembly)
  1134. .Distinct();
  1135. foreach (var assembly in assemblies)
  1136. {
  1137. Logger.LogDebug("Found API endpoints in plugin {Name}", assembly.FullName);
  1138. yield return assembly;
  1139. }
  1140. }
  1141. public virtual void LaunchUrl(string url)
  1142. {
  1143. if (!CanLaunchWebBrowser)
  1144. {
  1145. throw new NotSupportedException();
  1146. }
  1147. var process = new Process
  1148. {
  1149. StartInfo = new ProcessStartInfo
  1150. {
  1151. FileName = url,
  1152. UseShellExecute = true,
  1153. ErrorDialog = false
  1154. },
  1155. EnableRaisingEvents = true
  1156. };
  1157. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1158. try
  1159. {
  1160. process.Start();
  1161. }
  1162. catch (Exception ex)
  1163. {
  1164. Logger.LogError(ex, "Error launching url: {url}", url);
  1165. throw;
  1166. }
  1167. }
  1168. private bool _disposed = false;
  1169. /// <summary>
  1170. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1171. /// </summary>
  1172. public void Dispose()
  1173. {
  1174. Dispose(true);
  1175. GC.SuppressFinalize(this);
  1176. }
  1177. /// <summary>
  1178. /// Releases unmanaged and - optionally - managed resources.
  1179. /// </summary>
  1180. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1181. protected virtual void Dispose(bool dispose)
  1182. {
  1183. if (_disposed)
  1184. {
  1185. return;
  1186. }
  1187. if (dispose)
  1188. {
  1189. var type = GetType();
  1190. Logger.LogInformation("Disposing {Type}", type.Name);
  1191. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1192. _disposableParts.Clear();
  1193. foreach (var part in parts)
  1194. {
  1195. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1196. try
  1197. {
  1198. part.Dispose();
  1199. }
  1200. catch (Exception ex)
  1201. {
  1202. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1203. }
  1204. }
  1205. }
  1206. _disposed = true;
  1207. }
  1208. }
  1209. internal class CertificateInfo
  1210. {
  1211. public string Path { get; set; }
  1212. public string Password { get; set; }
  1213. }
  1214. }