ApplicationHost.cs 54 KB

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