ApplicationHost.cs 54 KB

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