ApplicationHost.cs 56 KB

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