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