ApplicationHost.cs 54 KB

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