ApplicationHost.cs 55 KB

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