ApplicationHost.cs 54 KB

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