2
0

ApplicationHost.cs 55 KB

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