2
0

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