ApplicationHost.cs 54 KB

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