ApplicationHost.cs 56 KB

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