2
0

ApplicationHost.cs 55 KB

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