ApplicationHost.cs 55 KB

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