ApplicationHost.cs 55 KB

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