ApplicationHost.cs 54 KB

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