ApplicationHost.cs 54 KB

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