ApplicationHost.cs 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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. using Prometheus.DotNetRuntime;
  109. namespace Emby.Server.Implementations
  110. {
  111. /// <summary>
  112. /// Class CompositionRoot.
  113. /// </summary>
  114. public abstract class ApplicationHost : IServerApplicationHost, IDisposable
  115. {
  116. /// <summary>
  117. /// The environment variable prefixes to log at server startup.
  118. /// </summary>
  119. private static readonly string[] _relevantEnvVarPrefixes = { "JELLYFIN_", "DOTNET_", "ASPNETCORE_" };
  120. private readonly IFileSystem _fileSystemManager;
  121. private readonly INetworkManager _networkManager;
  122. private readonly IXmlSerializer _xmlSerializer;
  123. private readonly IStartupOptions _startupOptions;
  124. private IMediaEncoder _mediaEncoder;
  125. private ISessionManager _sessionManager;
  126. private IHttpServer _httpServer;
  127. private IHttpClient _httpClient;
  128. /// <summary>
  129. /// Gets a value indicating whether this instance can self restart.
  130. /// </summary>
  131. public bool CanSelfRestart => _startupOptions.RestartPath != null;
  132. public virtual bool CanLaunchWebBrowser
  133. {
  134. get
  135. {
  136. if (!Environment.UserInteractive)
  137. {
  138. return false;
  139. }
  140. if (_startupOptions.IsService)
  141. {
  142. return false;
  143. }
  144. if (OperatingSystem.Id == OperatingSystemId.Windows
  145. || OperatingSystem.Id == OperatingSystemId.Darwin)
  146. {
  147. return true;
  148. }
  149. return false;
  150. }
  151. }
  152. /// <summary>
  153. /// Occurs when [has pending restart changed].
  154. /// </summary>
  155. public event EventHandler HasPendingRestartChanged;
  156. /// <summary>
  157. /// Gets a value indicating whether this instance has changes that require the entire application to restart.
  158. /// </summary>
  159. /// <value><c>true</c> if this instance has pending application restart; otherwise, <c>false</c>.</value>
  160. public bool HasPendingRestart { get; private set; }
  161. /// <inheritdoc />
  162. public bool IsShuttingDown { get; private set; }
  163. /// <summary>
  164. /// Gets the logger.
  165. /// </summary>
  166. protected ILogger Logger { get; }
  167. private IPlugin[] _plugins;
  168. /// <summary>
  169. /// Gets the plugins.
  170. /// </summary>
  171. /// <value>The plugins.</value>
  172. public IReadOnlyList<IPlugin> Plugins => _plugins;
  173. /// <summary>
  174. /// Gets the logger factory.
  175. /// </summary>
  176. protected ILoggerFactory LoggerFactory { get; }
  177. /// <summary>
  178. /// Gets or sets the application paths.
  179. /// </summary>
  180. /// <value>The application paths.</value>
  181. protected ServerApplicationPaths ApplicationPaths { get; set; }
  182. /// <summary>
  183. /// Gets or sets all concrete types.
  184. /// </summary>
  185. /// <value>All concrete types.</value>
  186. private Type[] _allConcreteTypes;
  187. /// <summary>
  188. /// The disposable parts.
  189. /// </summary>
  190. private readonly List<IDisposable> _disposableParts = new List<IDisposable>();
  191. /// <summary>
  192. /// Gets the configuration manager.
  193. /// </summary>
  194. /// <value>The configuration manager.</value>
  195. protected IConfigurationManager ConfigurationManager { get; set; }
  196. /// <summary>
  197. /// Gets or sets the service provider.
  198. /// </summary>
  199. public IServiceProvider ServiceProvider { get; set; }
  200. /// <summary>
  201. /// Gets the http port for the webhost.
  202. /// </summary>
  203. public int HttpPort { get; private set; }
  204. /// <summary>
  205. /// Gets the https port for the webhost.
  206. /// </summary>
  207. public int HttpsPort { get; private set; }
  208. /// <summary>
  209. /// Gets the server configuration manager.
  210. /// </summary>
  211. /// <value>The server configuration manager.</value>
  212. public IServerConfigurationManager ServerConfigurationManager => (IServerConfigurationManager)ConfigurationManager;
  213. /// <summary>
  214. /// Initializes a new instance of the <see cref="ApplicationHost" /> class.
  215. /// </summary>
  216. public ApplicationHost(
  217. ServerApplicationPaths applicationPaths,
  218. ILoggerFactory loggerFactory,
  219. IStartupOptions options,
  220. IFileSystem fileSystem,
  221. INetworkManager networkManager)
  222. {
  223. _xmlSerializer = new MyXmlSerializer();
  224. _networkManager = networkManager;
  225. networkManager.LocalSubnetsFn = GetConfiguredLocalSubnets;
  226. ApplicationPaths = applicationPaths;
  227. LoggerFactory = loggerFactory;
  228. _fileSystemManager = fileSystem;
  229. ConfigurationManager = new ServerConfigurationManager(ApplicationPaths, LoggerFactory, _xmlSerializer, _fileSystemManager);
  230. Logger = LoggerFactory.CreateLogger<ApplicationHost>();
  231. _startupOptions = options;
  232. // Initialize runtime stat collection
  233. if (ServerConfigurationManager.Configuration.EnableMetrics)
  234. {
  235. DotNetRuntimeStatsBuilder.Default().StartCollecting();
  236. }
  237. fileSystem.AddShortcutHandler(new MbLinkShortcutHandler(fileSystem));
  238. _networkManager.NetworkChanged += OnNetworkChanged;
  239. CertificateInfo = new CertificateInfo
  240. {
  241. Path = ServerConfigurationManager.Configuration.CertificatePath,
  242. Password = ServerConfigurationManager.Configuration.CertificatePassword
  243. };
  244. Certificate = GetCertificate(CertificateInfo);
  245. }
  246. public string ExpandVirtualPath(string path)
  247. {
  248. var appPaths = ApplicationPaths;
  249. return path.Replace(appPaths.VirtualDataPath, appPaths.DataPath, StringComparison.OrdinalIgnoreCase)
  250. .Replace(appPaths.VirtualInternalMetadataPath, appPaths.InternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  251. }
  252. public string ReverseVirtualPath(string path)
  253. {
  254. var appPaths = ApplicationPaths;
  255. return path.Replace(appPaths.DataPath, appPaths.VirtualDataPath, StringComparison.OrdinalIgnoreCase)
  256. .Replace(appPaths.InternalMetadataPath, appPaths.VirtualInternalMetadataPath, StringComparison.OrdinalIgnoreCase);
  257. }
  258. private string[] GetConfiguredLocalSubnets()
  259. {
  260. return ServerConfigurationManager.Configuration.LocalNetworkSubnets;
  261. }
  262. private void OnNetworkChanged(object sender, EventArgs e)
  263. {
  264. _validAddressResults.Clear();
  265. }
  266. /// <inheritdoc />
  267. public Version ApplicationVersion { get; } = typeof(ApplicationHost).Assembly.GetName().Version;
  268. /// <inheritdoc />
  269. public string ApplicationVersionString { get; } = typeof(ApplicationHost).Assembly.GetName().Version.ToString(3);
  270. /// <summary>
  271. /// Gets the current application user agent.
  272. /// </summary>
  273. /// <value>The application user agent.</value>
  274. public string ApplicationUserAgent => Name.Replace(' ', '-') + "/" + ApplicationVersionString;
  275. /// <summary>
  276. /// Gets the email address for use within a comment section of a user agent field.
  277. /// Presently used to provide contact information to MusicBrainz service.
  278. /// </summary>
  279. public string ApplicationUserAgentAddress { get; } = "team@jellyfin.org";
  280. /// <summary>
  281. /// Gets the current application name.
  282. /// </summary>
  283. /// <value>The application name.</value>
  284. public string ApplicationProductName { get; } = FileVersionInfo.GetVersionInfo(Assembly.GetEntryAssembly().Location).ProductName;
  285. private DeviceId _deviceId;
  286. public string SystemId
  287. {
  288. get
  289. {
  290. if (_deviceId == null)
  291. {
  292. _deviceId = new DeviceId(ApplicationPaths, LoggerFactory);
  293. }
  294. return _deviceId.Value;
  295. }
  296. }
  297. /// <inheritdoc/>
  298. public string Name => ApplicationProductName;
  299. /// <summary>
  300. /// Creates an instance of type and resolves all constructor dependencies.
  301. /// </summary>
  302. /// <param name="type">The type.</param>
  303. /// <returns>System.Object.</returns>
  304. public object CreateInstance(Type type)
  305. => ActivatorUtilities.CreateInstance(ServiceProvider, type);
  306. /// <summary>
  307. /// Creates an instance of type and resolves all constructor dependencies.
  308. /// </summary>
  309. /// /// <typeparam name="T">The type.</typeparam>
  310. /// <returns>T.</returns>
  311. public T CreateInstance<T>()
  312. => ActivatorUtilities.CreateInstance<T>(ServiceProvider);
  313. /// <summary>
  314. /// Creates the instance safe.
  315. /// </summary>
  316. /// <param name="type">The type.</param>
  317. /// <returns>System.Object.</returns>
  318. protected object CreateInstanceSafe(Type type)
  319. {
  320. try
  321. {
  322. Logger.LogDebug("Creating instance of {Type}", type);
  323. return ActivatorUtilities.CreateInstance(ServiceProvider, type);
  324. }
  325. catch (Exception ex)
  326. {
  327. Logger.LogError(ex, "Error creating {Type}", type);
  328. return null;
  329. }
  330. }
  331. /// <summary>
  332. /// Resolves this instance.
  333. /// </summary>
  334. /// <typeparam name="T">The type</typeparam>
  335. /// <returns>``0.</returns>
  336. public T Resolve<T>() => ServiceProvider.GetService<T>();
  337. /// <summary>
  338. /// Gets the export types.
  339. /// </summary>
  340. /// <typeparam name="T">The type.</typeparam>
  341. /// <returns>IEnumerable{Type}.</returns>
  342. public IEnumerable<Type> GetExportTypes<T>()
  343. {
  344. var currentType = typeof(T);
  345. return _allConcreteTypes.Where(i => currentType.IsAssignableFrom(i));
  346. }
  347. /// <inheritdoc />
  348. public IReadOnlyCollection<T> GetExports<T>(bool manageLifetime = true)
  349. {
  350. // Convert to list so this isn't executed for each iteration
  351. var parts = GetExportTypes<T>()
  352. .Select(CreateInstanceSafe)
  353. .Where(i => i != null)
  354. .Cast<T>()
  355. .ToList();
  356. if (manageLifetime)
  357. {
  358. lock (_disposableParts)
  359. {
  360. _disposableParts.AddRange(parts.OfType<IDisposable>());
  361. }
  362. }
  363. return parts;
  364. }
  365. /// <summary>
  366. /// Runs the startup tasks.
  367. /// </summary>
  368. /// <returns><see cref="Task" />.</returns>
  369. public async Task RunStartupTasksAsync()
  370. {
  371. Logger.LogInformation("Running startup tasks");
  372. Resolve<ITaskManager>().AddTasks(GetExports<IScheduledTask>(false));
  373. ConfigurationManager.ConfigurationUpdated += OnConfigurationUpdated;
  374. _mediaEncoder.SetFFmpegPath();
  375. Logger.LogInformation("ServerId: {0}", SystemId);
  376. var entryPoints = GetExports<IServerEntryPoint>();
  377. var stopWatch = new Stopwatch();
  378. stopWatch.Start();
  379. await Task.WhenAll(StartEntryPoints(entryPoints, true)).ConfigureAwait(false);
  380. Logger.LogInformation("Executed all pre-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  381. Logger.LogInformation("Core startup complete");
  382. _httpServer.GlobalResponse = null;
  383. stopWatch.Restart();
  384. await Task.WhenAll(StartEntryPoints(entryPoints, false)).ConfigureAwait(false);
  385. Logger.LogInformation("Executed all post-startup entry points in {Elapsed:g}", stopWatch.Elapsed);
  386. stopWatch.Stop();
  387. }
  388. private IEnumerable<Task> StartEntryPoints(IEnumerable<IServerEntryPoint> entryPoints, bool isBeforeStartup)
  389. {
  390. foreach (var entryPoint in entryPoints)
  391. {
  392. if (isBeforeStartup != (entryPoint is IRunBeforeStartup))
  393. {
  394. continue;
  395. }
  396. Logger.LogDebug("Starting entry point {Type}", entryPoint.GetType());
  397. yield return entryPoint.RunAsync();
  398. }
  399. }
  400. /// <inheritdoc/>
  401. public void Init(IServiceCollection serviceCollection)
  402. {
  403. HttpPort = ServerConfigurationManager.Configuration.HttpServerPortNumber;
  404. HttpsPort = ServerConfigurationManager.Configuration.HttpsPortNumber;
  405. // Safeguard against invalid configuration
  406. if (HttpPort == HttpsPort)
  407. {
  408. HttpPort = ServerConfiguration.DefaultHttpPort;
  409. HttpsPort = ServerConfiguration.DefaultHttpsPort;
  410. }
  411. if (Plugins != null)
  412. {
  413. var pluginBuilder = new StringBuilder();
  414. foreach (var plugin in Plugins)
  415. {
  416. pluginBuilder.AppendLine(
  417. string.Format(
  418. CultureInfo.InvariantCulture,
  419. "{0} {1}",
  420. plugin.Name,
  421. plugin.Version));
  422. }
  423. Logger.LogInformation("Plugins: {Plugins}", pluginBuilder.ToString());
  424. }
  425. DiscoverTypes();
  426. RegisterServices(serviceCollection);
  427. }
  428. public async Task ExecuteWebsocketHandlerAsync(HttpContext context, Func<Task> next)
  429. {
  430. if (!context.WebSockets.IsWebSocketRequest)
  431. {
  432. await next().ConfigureAwait(false);
  433. return;
  434. }
  435. await _httpServer.ProcessWebSocketRequest(context).ConfigureAwait(false);
  436. }
  437. public async Task ExecuteHttpHandlerAsync(HttpContext context, Func<Task> next)
  438. {
  439. if (context.WebSockets.IsWebSocketRequest)
  440. {
  441. await next().ConfigureAwait(false);
  442. return;
  443. }
  444. var request = context.Request;
  445. var response = context.Response;
  446. var localPath = context.Request.Path.ToString();
  447. var req = new WebSocketSharpRequest(request, response, request.Path, LoggerFactory.CreateLogger<WebSocketSharpRequest>());
  448. await _httpServer.RequestHandler(req, request.GetDisplayUrl(), request.Host.ToString(), localPath, context.RequestAborted).ConfigureAwait(false);
  449. }
  450. /// <summary>
  451. /// Registers services/resources with the service collection that will be available via DI.
  452. /// </summary>
  453. protected virtual void RegisterServices(IServiceCollection serviceCollection)
  454. {
  455. serviceCollection.AddSingleton(_startupOptions);
  456. serviceCollection.AddMemoryCache();
  457. serviceCollection.AddSingleton(ConfigurationManager);
  458. serviceCollection.AddSingleton<IApplicationHost>(this);
  459. serviceCollection.AddSingleton<IApplicationPaths>(ApplicationPaths);
  460. serviceCollection.AddSingleton<IJsonSerializer, JsonSerializer>();
  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, bool forceHttp = false)
  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, forceHttp);
  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, bool forceHttp = false)
  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, forceHttp);
  1003. }
  1004. return GetLocalApiUrl(ipAddress.ToString(), forceHttp);
  1005. }
  1006. /// <inheritdoc />
  1007. public string GetLocalApiUrl(ReadOnlySpan<char> host, bool forceHttp = false)
  1008. {
  1009. var url = new StringBuilder(64);
  1010. bool useHttps = EnableHttps && !forceHttp;
  1011. url.Append(useHttps ? "https://" : "http://")
  1012. .Append(host)
  1013. .Append(':')
  1014. .Append(useHttps ? HttpsPort : HttpPort);
  1015. string baseUrl = ServerConfigurationManager.Configuration.BaseUrl;
  1016. if (baseUrl.Length != 0)
  1017. {
  1018. url.Append(baseUrl);
  1019. }
  1020. return url.ToString();
  1021. }
  1022. public Task<List<IPAddress>> GetLocalIpAddresses(CancellationToken cancellationToken)
  1023. {
  1024. return GetLocalIpAddressesInternal(true, 0, cancellationToken);
  1025. }
  1026. private async Task<List<IPAddress>> GetLocalIpAddressesInternal(bool allowLoopback, int limit, CancellationToken cancellationToken)
  1027. {
  1028. var addresses = ServerConfigurationManager
  1029. .Configuration
  1030. .LocalNetworkAddresses
  1031. .Select(NormalizeConfiguredLocalAddress)
  1032. .Where(i => i != null)
  1033. .ToList();
  1034. if (addresses.Count == 0)
  1035. {
  1036. addresses.AddRange(_networkManager.GetLocalIpAddresses(ServerConfigurationManager.Configuration.IgnoreVirtualInterfaces));
  1037. }
  1038. var resultList = new List<IPAddress>();
  1039. foreach (var address in addresses)
  1040. {
  1041. if (!allowLoopback)
  1042. {
  1043. if (address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.IPv6Loopback))
  1044. {
  1045. continue;
  1046. }
  1047. }
  1048. var valid = await IsIpAddressValidAsync(address, cancellationToken).ConfigureAwait(false);
  1049. if (valid)
  1050. {
  1051. resultList.Add(address);
  1052. if (limit > 0 && resultList.Count >= limit)
  1053. {
  1054. return resultList;
  1055. }
  1056. }
  1057. }
  1058. return resultList;
  1059. }
  1060. public IPAddress NormalizeConfiguredLocalAddress(string address)
  1061. {
  1062. var index = address.Trim('/').IndexOf('/');
  1063. if (index != -1)
  1064. {
  1065. address = address.Substring(index + 1);
  1066. }
  1067. if (IPAddress.TryParse(address.Trim('/'), out IPAddress result))
  1068. {
  1069. return result;
  1070. }
  1071. return null;
  1072. }
  1073. private readonly ConcurrentDictionary<string, bool> _validAddressResults = new ConcurrentDictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
  1074. private async Task<bool> IsIpAddressValidAsync(IPAddress address, CancellationToken cancellationToken)
  1075. {
  1076. if (address.Equals(IPAddress.Loopback)
  1077. || address.Equals(IPAddress.IPv6Loopback))
  1078. {
  1079. return true;
  1080. }
  1081. var apiUrl = GetLocalApiUrl(address);
  1082. apiUrl += "/system/ping";
  1083. if (_validAddressResults.TryGetValue(apiUrl, out var cachedResult))
  1084. {
  1085. return cachedResult;
  1086. }
  1087. try
  1088. {
  1089. using (var response = await _httpClient.SendAsync(
  1090. new HttpRequestOptions
  1091. {
  1092. Url = apiUrl,
  1093. LogErrorResponseBody = false,
  1094. BufferContent = false,
  1095. CancellationToken = cancellationToken
  1096. }, HttpMethod.Post).ConfigureAwait(false))
  1097. {
  1098. using (var reader = new StreamReader(response.Content))
  1099. {
  1100. var result = await reader.ReadToEndAsync().ConfigureAwait(false);
  1101. var valid = string.Equals(Name, result, StringComparison.OrdinalIgnoreCase);
  1102. _validAddressResults.AddOrUpdate(apiUrl, valid, (k, v) => valid);
  1103. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, valid);
  1104. return valid;
  1105. }
  1106. }
  1107. }
  1108. catch (OperationCanceledException)
  1109. {
  1110. Logger.LogDebug("Ping test result to {0}. Success: {1}", apiUrl, "Cancelled");
  1111. throw;
  1112. }
  1113. catch (Exception ex)
  1114. {
  1115. Logger.LogDebug(ex, "Ping test result to {0}. Success: {1}", apiUrl, false);
  1116. _validAddressResults.AddOrUpdate(apiUrl, false, (k, v) => false);
  1117. return false;
  1118. }
  1119. }
  1120. public string FriendlyName =>
  1121. string.IsNullOrEmpty(ServerConfigurationManager.Configuration.ServerName)
  1122. ? Environment.MachineName
  1123. : ServerConfigurationManager.Configuration.ServerName;
  1124. /// <summary>
  1125. /// Shuts down.
  1126. /// </summary>
  1127. public async Task Shutdown()
  1128. {
  1129. if (IsShuttingDown)
  1130. {
  1131. return;
  1132. }
  1133. IsShuttingDown = true;
  1134. try
  1135. {
  1136. await _sessionManager.SendServerShutdownNotification(CancellationToken.None).ConfigureAwait(false);
  1137. }
  1138. catch (Exception ex)
  1139. {
  1140. Logger.LogError(ex, "Error sending server shutdown notification");
  1141. }
  1142. ShutdownInternal();
  1143. }
  1144. protected abstract void ShutdownInternal();
  1145. public event EventHandler HasUpdateAvailableChanged;
  1146. private bool _hasUpdateAvailable;
  1147. public bool HasUpdateAvailable
  1148. {
  1149. get => _hasUpdateAvailable;
  1150. set
  1151. {
  1152. var fireEvent = value && !_hasUpdateAvailable;
  1153. _hasUpdateAvailable = value;
  1154. if (fireEvent)
  1155. {
  1156. HasUpdateAvailableChanged?.Invoke(this, EventArgs.Empty);
  1157. }
  1158. }
  1159. }
  1160. /// <summary>
  1161. /// Removes the plugin.
  1162. /// </summary>
  1163. /// <param name="plugin">The plugin.</param>
  1164. public void RemovePlugin(IPlugin plugin)
  1165. {
  1166. var list = _plugins.ToList();
  1167. list.Remove(plugin);
  1168. _plugins = list.ToArray();
  1169. }
  1170. public virtual void LaunchUrl(string url)
  1171. {
  1172. if (!CanLaunchWebBrowser)
  1173. {
  1174. throw new NotSupportedException();
  1175. }
  1176. var process = new Process
  1177. {
  1178. StartInfo = new ProcessStartInfo
  1179. {
  1180. FileName = url,
  1181. UseShellExecute = true,
  1182. ErrorDialog = false
  1183. },
  1184. EnableRaisingEvents = true
  1185. };
  1186. process.Exited += (sender, args) => ((Process)sender).Dispose();
  1187. try
  1188. {
  1189. process.Start();
  1190. }
  1191. catch (Exception ex)
  1192. {
  1193. Logger.LogError(ex, "Error launching url: {url}", url);
  1194. throw;
  1195. }
  1196. }
  1197. public virtual void EnableLoopback(string appName)
  1198. {
  1199. }
  1200. private bool _disposed = false;
  1201. /// <summary>
  1202. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  1203. /// </summary>
  1204. public void Dispose()
  1205. {
  1206. Dispose(true);
  1207. GC.SuppressFinalize(this);
  1208. }
  1209. /// <summary>
  1210. /// Releases unmanaged and - optionally - managed resources.
  1211. /// </summary>
  1212. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1213. protected virtual void Dispose(bool dispose)
  1214. {
  1215. if (_disposed)
  1216. {
  1217. return;
  1218. }
  1219. if (dispose)
  1220. {
  1221. var type = GetType();
  1222. Logger.LogInformation("Disposing {Type}", type.Name);
  1223. var parts = _disposableParts.Distinct().Where(i => i.GetType() != type).ToList();
  1224. _disposableParts.Clear();
  1225. foreach (var part in parts)
  1226. {
  1227. Logger.LogInformation("Disposing {Type}", part.GetType().Name);
  1228. try
  1229. {
  1230. part.Dispose();
  1231. }
  1232. catch (Exception ex)
  1233. {
  1234. Logger.LogError(ex, "Error disposing {Type}", part.GetType().Name);
  1235. }
  1236. }
  1237. }
  1238. _disposed = true;
  1239. }
  1240. }
  1241. internal class CertificateInfo
  1242. {
  1243. public string Path { get; set; }
  1244. public string Password { get; set; }
  1245. }
  1246. }