ApplicationHost.cs 56 KB

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