ApplicationHost.cs 56 KB

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