ApplicationHost.cs 54 KB

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