ApplicationHost.cs 54 KB

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